Welcome to the most active Linux Forum on the web.
 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?
 User Name Remember Me? Password
 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.

 Posting Rules You may not post new threads You may not post replies You may not post attachments You may not edit your posts BB code is On Smilies are On [IMG] code is Off HTML code is Off Forum Rules

 Similar Threads Thread Thread Starter Forum Replies Last Post sajith Programming 3 10-06-2005 10:59 PM zero79 Linux - Software 1 08-29-2005 09:30 PM nadroj Programming 6 07-11-2005 04:52 PM carboncopy Slackware 1 05-28-2004 09:09 AM alaios Programming 4 04-24-2004 02:10 PM

LinuxQuestions.org

All times are GMT -5. The time now is 08:58 PM.

 Contact Us - Advertising Info - Rules - LQ Merchandise - Donations - Contributing Member - LQ Sitemap -