LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How to convert a float to its binary or hex representation in Python? (https://www.linuxquestions.org/questions/programming-9/how-to-convert-a-float-to-its-binary-or-hex-representation-in-python-358639/)

zero79 08-30-2005 07:10 PM

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()


deiussum 09-01-2005 10:19 AM

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.


All times are GMT -5. The time now is 10:12 AM.