简体   繁体   中英

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)

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]

'float.hex()' method is used to convert a floating point number to its hexadecimal value. Similarly, we can use 'float.fromhex()' method to convert a hexadecimal string value to its floating point representation. 'hex()' is an instance method but 'fromhex()' is a class method.

Below is the code which will help you..

#define numpy array
np_arr = np.array([1.2,3.4,2.6,2.1,15,10], dtype = np.float32)

#convert numpy array to hex
np_arr_hex = np.array([float.hex(float(x)) for x in np_arr])

#back to float with upto 4 decimal places
np_arr_float = np.array([round(float.fromhex(x),1) for x in np_arr_hex])

#print both arrays
np_arr_hex,np_arr_float

Output:

np_arr_hex

(array(['0x1.3333340000000p+0', '0x1.b333340000000p+1',
    '0x1.4ccccc0000000p+1', '0x1.0ccccc0000000p+1',
    '0x1.e000000000000p+3', '0x1.4000000000000p+3'], dtype='<U20')

np_arr_float

array([ 1.2,  3.4,  2.6,  2.1, 15. , 10. ]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM