I have a program which reads in a binary file of single precision IBM floating points numbers. The goal is to convert these to IEEE754 floating points (in binary format). Currently I am reading in the binary IBM number, converting it to a float and then converting that into its IEEE754 format (single precision). For some reason I am not getting quite the output I want.
My input:
11000010011101101010000000000000
Output I want:
11000010111011010100000000000000
Output i am getting:
1100000001011101101010000000000000000000000000000000000000000000
Code:
import struct
getBin = lambda x: x > 0 and str(bin(x))[2:] or "-" + str(bin(x))[3:]
def floatToBinary64(value):
val = struct.unpack('Q', struct.pack('d', value))[0]
return getBin(val)
with open("test.bin", "rb") as f:
while True:
ibm = f.read(32);
if not ibm:
break
print(ibm)
ibm = int(ibm, 2)
sign = (ibm >> 31) & 0x01
exponent = (ibm >> 24) & 0x7f
mantissa = (ibm & 0x00ffffff) / pow(2, 24)
decimal = (1 - 2 * sign) * mantissa * float(pow(16, exponent - 64))
print(decimal)
binary = floatToBinary64(decimal)
print(binary)
How can I modify this code to get my desired output?