Python Forum
convert array of numbers to byte array
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
convert array of numbers to byte array
#1
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.
Reply
#2
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.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
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.
Reply
#4
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Metasploit Graph and Append Array Difficulties Tuurbo46 37 756 May-21-2026, 09:31 AM
Last Post: Dustbunny
Big Grin [solved] how to associate value in an array? paul18fr 9 3,778 Aug-26-2025, 05:44 AM
Last Post: paul18fr
  Numpy, array(2d,bool), flipping regions. MvGulik 2 1,632 Oct-27-2024, 11:06 AM
Last Post: MvGulik
  JSON File - extract only the data in a nested array for CSV file shwfgd 2 2,250 Aug-26-2024, 10:14 PM
Last Post: shwfgd
  ValueError: could not broadcast input array from shape makingwithheld 1 5,657 Jul-06-2024, 03:02 PM
Last Post: paul18fr
  python code to calculate mean of an array of numbers using numpy viren 3 2,125 May-29-2024, 04:49 PM
Last Post: Gribouillis
  Writing a cycle to find the nearest point from the array Tysrusko 0 1,319 May-10-2024, 11:49 AM
Last Post: Tysrusko
  Elegant way to apply each element of an array to a dataframe? sawtooth500 7 4,880 Mar-29-2024, 05:51 PM
Last Post: deanhystad
  Concatenate array for 3D plotting armanditod 1 1,905 Mar-21-2024, 08:08 PM
Last Post: deanhystad
  Convert numpy array to image without loading it into RAM. DreamingInsanity 7 13,055 Feb-08-2024, 09:38 AM
Last Post: paul18fr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020