Support LQ: Use code LQ3 and save \$3 on Domain Registration
 Home Forums HCL Reviews Tutorials Articles Register Search Today's Posts Mark Forums Read
 LinuxQuestions.org How to convert a float to its binary or hex representation in Python?
 Programming This forum is for all programming questions. The question does not have to be directly related to Linux and any language is fair game.

Notices

 08-30-2005, 07:10 PM #1 zero79 Member   Registered: Nov 2003 Location: Ohio Distribution: Debian Unstable Posts: 460 Rep: How to convert a float to its binary or hex representation in Python? 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. Code: ```#!/usr/bin/python import array import random bfile = 'binary' N = 10 # generate a list of N random floats data = array.array('f') for cnt in range(0, N): data.append(random.random()) # 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] else: base16_float += hex(ascii_val)[2:4] print base16_float # write binary file bid = open(bfile, mode = 'w') bid.write(bstr) bid.close()``` Last edited by zero79; 08-30-2005 at 07:29 PM.
 09-01-2005, 10:19 AM #2 deiussum Member   Registered: Aug 2003 Location: Santa Clara, CA Distribution: Slackware Posts: 895 Rep: I'm far from being a Python expert, but if I understand what you want correctly, struct.pack may be what you are looking for. You can use that to get a binary format of various types.