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 ]
asked Mar 8, 2023 at 13:00
2
  • I have a couple of ideas, could you give an example input and expected output (in Python). Commented Mar 8, 2023 at 13:12
  • 1
    Have you looked at the included struct module? You can pack data into the struct in one format and unpack it in another. Commented Mar 8, 2023 at 13:19

1 Answer 1

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]
answered Mar 8, 2023 at 13:24
Sign up to request clarification or add additional context in comments.

2 Comments

Note: as opposed the the Typescript implementation, here you are actually creating new objects in each step.
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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.