0

I have data-points of hex-strings in a list.

I tried converting the list to string and then to a byte array. As I try to convert the byte array to float it only returns one value.

Code used is :

byteArrObj = bytearray(n, 'utf-8')
byteObj = bytes(byteArrObj)
byte8=bytearray.fromhex(b)
print(byte8)
floatvalue = struct.unpack('<f', byte8[:4])

This produces a tuple, like `(0.09273222088813782,).

How do I print all the float values from the list?

1
  • Just to be clear, are you expecting 0.927322 from 64 EA BD 3D or 0.09273222088813782? Commented Oct 9, 2020 at 0:14

1 Answer 1

1

First, let's make a function that converts one of the values:

def hexdump_to_float(text):
    return struct.unpack('<f', bytes.fromhex(text))[0]

Notice:

  1. I skip the step of finding byteArrObj or byteObj from your code, because they had no effect in your code and do not help solve the problem.

  2. I use the type bytes rather than bytearray because we don't need to modify the underlying data. (It's analogous to using a tuple rather than list.)

  3. I do not bother with slicing the data, because we already know there will be only 4 bytes, and because struct.unpack would ignore any extra data in the buffer anyway.

  4. To get the value out of the tuple that struct.unpack returns, I simply index into the tuple. That gives me a single float value.

So this is a simple one-line function, but it helps to make a function anyway since it gives a clear name for what we are doing.

The next step is to apply that to each element of the list. You can do this easily with, for example, a list comprehension:

my_floats = [hexdump_to_float(x) for x in my_hexdumps]
Sign up to request clarification or add additional context in comments.

1 Comment

It worked. Thank you so much. Highly appreciate that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.