Python Forum
convert array of numbers to byte array - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: convert array of numbers to byte array (/thread-29002.html)



convert array of numbers to byte array - adetheheat - Aug-13-2020

I have an array of numbers - some are 8 bits, some are 16 bit little endian. eg
1,120,340, 54238, 65132,
How do I convert them to one byte array ? I know the offsets in the array where the 8bit numbers and 16 bit numbers are.


RE: convert array of numbers to byte array - DeaD_EyE - Aug-13-2020

With the struct module.

import struct

uint16be = struct.Struct(">I")
int16be = struct.Struct(">h")
int16le = struct.Struct("<h")
int8 = struct.Struct("b")

my_numbers = 1, 120, 340, 54238, 65132

for number in my_numbers:
    value = uint16be.pack(number)
    print(value)
Output:
b'\x00\x00\x00\x01' b'\x00\x00\x00x' b'\x00\x00\x01T' b'\x00\x00\xd3\xde' b'\x00\x00\xfel'
Some of your numbers are too big for 16-bit signed integers.


RE: convert array of numbers to byte array - adetheheat - Aug-13-2020

that's not quite what I want. I want them as numbers not strings.
So for instance for this small array of uint8 and then a uint16 : 14,54274
I want the bytes obtained to be:
14,2,212

I could do it procedureraly but there's got to be a faster way.


RE: convert array of numbers to byte array - bowlofred - Aug-13-2020

The output of the struct isn't "strings", it's just a different packing.

Perhaps you just need divmod()

>>> divmod(54274,256)
(212, 2)
Close might be something like:
>>> l = [1,120,340, 54238, 65132]
>>> [x if x < 256 else divmod(x,256)[::-1] for x in l]
[1, 120, (84, 1), (222, 211), (108, 254)]
But you'd have to flatten the list later to remove the tuples.