0

Related to Python int to binary string?, I would like to know a pythonic way to get the IEEE-754 binary32 representation of a number of int, float, or double.

For example, 42.0 is to be converted to 1 10000100 01010 000000000000000000

zell
  • 9,830
  • 10
  • 62
  • 115

1 Answers1

1

Try this:

import struct

getBin = lambda x: x > 0 and str(bin(x))[2:] or "-" + str(bin(x))[3:]

def floatToBinary32(value):
    val = struct.unpack('I', struct.pack('f', value))[0]
    return getBin(val)

binstr = floatToBinary32(42.0)
print('Binary equivalent of 42.0:')
print(binstr + '\n')
alexisdevarennes
  • 5,437
  • 4
  • 24
  • 38
  • Thanks. Is there any build-in solution?To convert int to binary is easy: format(42,"b"), is there anything alike? – zell Mar 12 '20 at 11:55