1

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'@`\x00\x00'

I suppose the two x00 x00 represent hexadecimal values for each bytes used but what about the b and '@` ?

3
  • 1
    "I'm trying to convert a float into binary." - Can you give an example of what you mean by "binary"? What sort of output are you seeking? Commented Sep 25, 2017 at 17:00
  • 2
    The bytes object you received contains the bytes you need. You're just getting confused by how it's displayed. You don't need to fix anything. Commented Sep 25, 2017 at 17:01
  • @Robᵩ basically i want to convert a float like 3.5 into a binary value like : 01000000011000000000000000000000 ( in form of string ) Commented Sep 25, 2017 at 17:17

2 Answers 2

1

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 in b'@`\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)0 = 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).

Sign up to request clarification or add additional context in comments.

3 Comments

thanks. exactly what i need. just cant use the format function because we havent learned what that function does in class yet.
You can get similar information from the built-in function bin.
yes. but i cant use that function in class either. again i'll remember it, i will probably need it later
0

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'>

2 Comments

how do i interpret what i see ?
@oozma This. Is. An. Immutable. Iterable. Of. Ints.

Your Answer

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