Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert numpy array of float32 data type to hex format

I want to convert a numpy array, which is of float32 data type to its equivalent hexadecimal format, in Python 3.

This is the implementation I tried but it doesn't seem to work:

import numpy as np
np.set_printoptions(formatter={'float':hex})
np.array([1.2,3.4,2.6,2.1], dtype = np.float32)

like image 635
Pantelis Avatar asked Nov 15 '25 22:11

Pantelis


1 Answers

Python's float type has a built-in .hex() method. In the formatter, you can use a lambda to first cast the value to float, and then call .hex():

np.set_printoptions(formatter={'float':lambda x:float(x).hex()})

For the following array:

arr = np.array([1.2,3.4,2.6,2.1], dtype = np.float32)
print(arr)

The output is:

[0x1.3333340000000p+0 0x1.b333340000000p+1 0x1.4ccccc0000000p+1
 0x1.0ccccc0000000p+1]
like image 70
glhr Avatar answered Nov 18 '25 13:11

glhr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!