Skip to content Skip to sidebar Skip to footer

How To Convert A Float Into Binary Using Struct.unpack?

I'm trying to convert a float into binary. I'm using the module struct. For instance, with the value of 3.5, when I execute this line : struct.pack('>f',3.5) I get this : b'@`

Solution 1:

There's no problem - the b'' literal is already binary bytes type (an old tradition, since 2.x).

>>> struct.pack('>f',3.5)
b'@`\x00\x00'>>> a = struct.pack('>f',3.5)
>>> type(a)
<class'bytes'>

Solution 2:

The format string '>f' means

'f' IEEE 754 binary32 (4 bytes, like a C float)

'>'big-endian byte order, standard size

That's documented here. The characters @ and ` are just part of your numeric data (3.5) when represented as ASCII. It's probably more helpful to look at these 4 bytes represented as binary:

>>> format(ord('@'), '08b')
'01000000'>>> format(ord('`'), '08b')
'01100000'>>> format(ord('\x00'), '08b')
'00000000'

So concatenated as a 32-bit float, that's has a binary representation like this:

>>> ''.join(format(x, '08b') for x inb'@`\x00\x00')
'01000000011000000000000000000000'

To convert the binary representation back to float by hand, read about single-precision floating-point format here, and split it up into components instead of bytes. This is sign bit, exponent (8 bit unsigned int, offset-encoded), and fraction (23 bits):

0 10000000 11000000000000000000000

The exponent here is just 1, because that representation offset by 127:

>>>int('10000000', 2) - 127
1

The fractional part is like 1.112, i.e.

>>>(2**0 + 2**-1 + 2**-2)*2
3.5

With a positive sign bit (-1) = 1, and an exponent 1, that's the number 3.5 (and it happens to be one of the numbers which can be represented exactly as a float).

Post a Comment for "How To Convert A Float Into Binary Using Struct.unpack?"