Home > front end >  Convert an array of 16 bit integers to an array of floats (IEEE 754)
Convert an array of 16 bit integers to an array of floats (IEEE 754)

Time:01-01

The task is to map/convert an array of 16 bit integers to an array of floats. The floats are encoded in IEEE 754 format. Each two elements of the array convert to one float.

This snippet does work. However I wonder if there is a more elegant/performant way to achieve the same result. Array a can have thousands of elements.

#!/usr/bin/env python
import struct

a = [ 16429, 468, 16428, 45554 ]
#b = [ 2.7217094898223877, 2.6983609199523926 ]
b = []

for i in range(0,len(a)>>1):
    b.append( struct.unpack(">f", ((a[2*i 0]<<16) a[2*i 1]).to_bytes(4, 'big') )[0] )

print( a )
print( b )

CodePudding user response:

Just making the struct functions do the work is ~10 times faster for me with thousands of elements:

n = len(a)
packed = struct.pack(f'>{n}H', *a)
b = struct.unpack(f'>{n//2}f', packed)

(Strictly speaking, I don't exactly get "the same result", as I get the floats in a tuple instead of a list. But you keep saying "array", and a tuple is just as much an array as a list is. And you might not need a list. If you do, converting to list is trivial and takes only very little extra time.)

CodePudding user response:

Technically you can swap the merging and int-byte conversion, so do the conversion on the 16-bit numbers, and merge the bytes objects instead, but I can't say it's nicer:

it=(number.to_bytes(2,'big') for number in a)
print([struct.unpack(">f",b''.join(pair))[0] for pair in zip(it,it)])

I have to add that I like the other answer more, just posting this one because I worked on it. Also, the memory footprint of this one may be better though (not a concern with thousands of elements, but may matter when it's about gigabytes).

  • Related