Helen Che
Helen Che

Reputation: 2011

Convert integer back to 32-bit hex representation then to float?

Say I have some binary data that was converted to 32-bit integer instead of 32-bit floating point (little endian), how can I rectify this?

For example: 1155186688 should be 1750 float (00 C0 DA 44 hex).

Upvotes: 2

Views: 1077

Answers (1)

Alastair McCormack
Alastair McCormack

Reputation: 27744

Struct is used for packing and unpacking types into bytes.

Convert the integer back to bytes, then into a float:

struct.unpack('f', struct.pack('I', 1155186688))[0]

Or the long form:

>>> my_bytes = struct.pack('I', 1155186688) # 'I' = Unsigned Int
b'\x00\xc0\xdaD'
>>> my_float = struct.unpack('f', my_bytes)[0] # 'f' = float
1750 

Upvotes: 5

Related Questions