Question

I have some code in C# that converts bytes to float using BitConverter.ToSingle function, like this:

float tmp_float = BitConverter.ToSingle(jobBff, cnt);

As I found out from this link:

http://en.wikipedia.org/wiki/Single-precision_floating-point_format

four bytes go in (just not sure in what order), use 1 bit for sign, 8 bits for exponent, and the rest of the bits for the fraction.

In C# I just inform a buffer, the starting position, and C# does the rest of the job. Is there an equivalent function for that on Python? Or how can I convert those 4 bytes to a float?

Thanks!


Solution: as suggested by Kyle in the answer, I ended up using the code below, which worked for me.

def prepare_bytes_on_string(array):
    output = ''
    for i in range(0, len(array), 1):
        #Just as a reminder:
        #hex(x)                    #value: '0xffffbfde1605'
        #hex(x)[2:]                #value: 'ffffbfde1605'
        #hex(x)[2:].decode('hex')  #value: '\xff\xff\xbf\xde\x16\x05'
        output += hex(array[i])[2:].decode('hex')
    return output

bytes_array = [0x38, 0xcd, 0x87, 0xc0]
val = prepare_bytes_on_string(bytes_array)
output = unpack('f', val)
print output
Was it helpful?

Solution

Python has the struct module. You would want the struct.unpack( 'f', buffer ) method (possibly with some endianess adjustment, see the documentation for that).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top