Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hexadecimal string representation to floating number in python

From python documentation says that "the hexadecimal string 0x3.a7p10 represents the floating-point number (3 + 10./16 + 7./16**2) * 2.0**10, or 3740.0" so :

>>> float.fromhex('0x3.a7p10')

3740.0

then

>>> float.hex(3740.0)

'0x1.d380000000000p+11' (will give different presentation)

My question is how to convert '0x1.d380000000000p+11' in to floating number using calculation formula above and why classmethod float.hex and classmethod float.fromhex give different presentation.

Thankyou....

like image 939
Wira Bhakti Avatar asked Nov 27 '25 18:11

Wira Bhakti


1 Answers

'0x1.d380000000000p+11' means (1 + 13./16 + 3./16**2 + 8/16**3) * 2.0**11, which is equal to 3740.0. To convert this result, you can run float.fromhex('0x1.d380000000000p+11') which returns 3740.0 again.

float.hex gives you a normalized representation, which means that the factor in front of the 2**x is between 1 and 2. What the interpreter did, was shift the comma in the binary representation by one position: increase the exponent (from 10 to 11), and half the factor (0x3.a7 / 2 = 0x1.d38).

In general, in this normalized representation, the factor in front is between 1 and the base. For example, if you do print(2234.2e-34), you get 2.2342e-31. Here the leading factor is between 1 and 10 because e corresponds to 10**x.

like image 127
sauerburger Avatar answered Dec 01 '25 19:12

sauerburger