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