1
new Uint8Array(new Uint16Array([64]).buffer)

How can I achieve same result structure with pure Python? What is an equivalent of Uint8Array/Uint16Array?

I'm getting buffer from Uint16Array type here and cast to Uint8Array, however I'm not sure how can I achieve similar behavior in Python. I was trying to play with bytearray, but for me it looks different.

[EDIT]

const uint16 = new Uint16Array([32 + 32]);
const uint16buffer = uint16.buffer;

console.log('uint16', uint16);
console.log('uint16buffer', uint16buffer);

const uint8 = new Uint8Array(uint16buffer);
console.log('uint8', uint8);

const data = new Uint8Array(new Uint16Array([32 + 32]).buffer);

console.log('data', data);

Returns output like below:

uint16 Uint16Array(1) [ 64 ]
uint16buffer ArrayBuffer { [Uint8Contents]: <40 00>, byteLength: 2 }
uint8 Uint8Array(2) [ 64, 0 ]
data Uint8Array(2) [ 64, 0 ]
Tatarinho
  • 754
  • 2
  • 11
  • 31
  • I have a couple of ideas, could you give an example input and expected output (in Python). – Adam.Er8 Mar 08 '23 at 13:12
  • 1
    Have you looked at the included [struct](https://docs.python.org/3/library/struct.html) module? You can *pack* data into the struct in one format and *unpack* it in another. – import random Mar 08 '23 at 13:19

1 Answers1

0

For the special case of Uint16 and Uint18 you can use divmod to split each 2-byte number into 1-byte number, and use list comprehension to collect them to a list:

uint8_arr = [uint8 for uint16 in nums for uint8 in reversed(divmod(uint16, 256))]

For the general case, you can use struct to encode a list of ints as uint16 bytes, and then re-interpret them into a new list of ints, like this:

import struct
nums = list(range(254,265))
uint16_buffer = struct.pack('H'*len(nums), *nums)
uint8_arr = list(struct.unpack('B'*len(nums)*2, uint16_buffer))
print(uint8_arr)

Both would print:

[254, 0, 255, 0, 0, 1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 1, 7, 1, 8, 1]
Adam.Er8
  • 12,675
  • 3
  • 26
  • 38
  • Note: as opposed the the Typescript implementation, here you are actually creating new objects in each step. – Adam.Er8 Mar 08 '23 at 13:26
  • 1
    This doesn't take endianness into account, which may or may not be important in OP's usecase. There's also `int.to_bytes` and `int.from_bytes` these days. – AKX Mar 08 '23 at 13:47