Hi, I'm trying to use Python to determine the machine representation of an array of floats. This is the code I have so far, which does the job, but it's very hacky and not very efficient. I was thinking something could be done with bitwise masking. Any thoughts on making this more direct and efficient are greatly appreciated. A 'hexdump binary' indicates that the conversion is indeed correct.
bfile = 'binary'
N = 10
# generate a list of N random floats
data = array.array('f')
for cnt in range(0, N):
# convert float array to equivilent ascii
bstr = data.tostring()
# process each 4 byte float and convert to base16/hex representation
for cnt1 in range(0, len(bstr), 4):
base16_float = ''
# process bytes in same order as will be presented by hexdump
for cnt2 in [1, 0, 3, 2]:
ascii_val = ord(bstr[cnt1 + cnt2])
if ascii_val < 16:
base16_float += '0' + hex(ascii_val)[2:3]
base16_float += hex(ascii_val)[2:4]
# write binary file
bid = open(bfile, mode = 'w')