Home > front end >  Python hexidecimal byte interconversion oddity
Python hexidecimal byte interconversion oddity

Time:12-15

I must be missing something....

np.float32(0xc32).tobytes() # --> `b'\x00 CE'`
struct.pack('<f', 0xc32) # --> `b'\x00 CE'`

yet the following doesn't convert back...

np.float32(0xc32).tobytes().hex() # --> '00204345'
struct.pack('<f', 0xc32).hex() # --> '00204345'

anyone know the error here?

CodePudding user response:

As pointed out in the comments, my error was assumption about hex strings... the proper way to conduct this interconversion:

np.frombuffer(np.float32(0xc32).tobytes(), dtype=np.float32)
struct.unpack('<f',struct.pack('<f', 0xc32))

CodePudding user response:

The problem there is because thats the hex string of that value. As you convert it as a float, thats the hex representation of that float value.

  • Related