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
  Elegant way to apply each element of an array to a dataframe? sawtooth500 5 175 1 hour ago
Last Post: deanhystad
  Concatenate array for 3D plotting armanditod 1 191 Mar-21-2024, 08:08 PM
Last Post: deanhystad
  Convert numpy array to image without loading it into RAM. DreamingInsanity 7 5,725 Feb-08-2024, 09:38 AM
Last Post: paul18fr
  How Write Part of a Binary Array? Assembler 1 305 Jan-14-2024, 11:35 PM
Last Post: Gribouillis
  Loop over an an array of array Chendipeter 1 529 Nov-28-2023, 06:37 PM
Last Post: deanhystad
  How to remove some elements from an array in python? gohanhango 9 985 Nov-28-2023, 08:35 AM
Last Post: Gribouillis
  IPython errors for numpy array min/max methods muelaner 1 508 Nov-04-2023, 09:22 PM
Last Post: snippsat
  Convert np Array A to networkx G IanAnderson 2 629 Jul-05-2023, 11:42 AM
Last Post: IanAnderson
  Help using a dynamic array excel formula with XLWings FXMonkey 2 1,208 Jun-06-2023, 09:46 PM
Last Post: FXMonkey
  [Newbie] Multiple Array azhuda 3 954 Jun-01-2023, 04:29 AM
Last Post: azhuda

Forum Jump:

User Panel Messages

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