4

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)

2 Answers 2

4

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]
Sign up to request clarification or add additional context in comments.

Comments

0

‘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. ]))

3 Comments

Creating a new list containing the HEX values is inefficient and unneeded here. OP only wants to change the formatting of the existing list for display purposes.
Just added 'fromhex()' if needed.
I meant the first array, np_arr_hex. There is no need to create it at all. The original array can be formatted into hex directly using np.set_printoptions().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.