Reputation: 10204
Related to Convert int to binary string in Python, 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 01010000000000000000000
Upvotes: 0
Views: 286
Reputation: 10238
Use struct.pack
to create a 32-bit Big-endian floating point representation of value
to get 4 bytes. Now iterate over these to format into zero-padded binary, and join the result to one string. Finally, insert space (' '
) after sign bit and between exponent (8 bits) and fraction (23 bits).
import struct
def float32_bitstr(value):
bits = ''.join([f"{b:08b}" for b in struct.pack('>f', value)])
return bits[:1]+' '+bits[1:-23]+' '+bits[-23:]
print(f"{float32_bitstr(42.0)=}")
Output:
float32_bitstr(42.0)='0 10000100 01010000000000000000000'
BTW: For evaluating solutions, output via f"{expression=}"
can be very handy.
Upvotes: 1
Reputation: 5642
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')
Upvotes: 1