1

i have a list of several 4x6 bytes (32bit) values in byte format. Is there any possibility to convert these binary values efficient in 32bit integers in python?

There is the method int.from_bytes(xTest, byteorder='little', signed = True), but it would be very inefficient to loop through all the values. Maybe someone have an idea?

xTest = [b'\xf8\x80[\xf0', b'\x12\x81\x87\xef', b'-\x81\xc0\xee', b'I\x81\xf9\xed']

Weevil
  • 87
  • 1
  • 3
  • 8
  • perhaps you can use `map()` – Mick_ Mar 31 '18 at 12:55
  • join the list to one string and use `struct` or `numpy`. – Daniel Mar 31 '18 at 12:58
  • I don't understand why you think that `int.from_bytes()` is inefficient. According to this comment https://stackoverflow.com/questions/444591/convert-a-string-of-bytes-into-an-int-python it outperforms `struct.unpack`. Change your call to `int.from_bytes(b''.join(xTest), byteorder='little', signed = True)`, otherwise it won't work. – BoarGules Mar 31 '18 at 14:42
  • Thanks for reply, if i use the int.from_bytes() in this way i would get one number of the whole list. But i want to get 4 32bit integers. So i would need to loop through it or is there another possibility? – Weevil Mar 31 '18 at 14:57

1 Answers1

2

Use list comprehension to apply the same operator to each of the element of your original xTest list:

int_list = [int.from_bytes(x, byteorder='little', signed = True) for x in xTest]

Here x loops through each of the element (thus, your 4 bytes) of xTest and thus allows you to apply the same operator to each of them.

JohanL
  • 6,671
  • 1
  • 12
  • 26