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 ]
-
I have a couple of ideas, could you give an example input and expected output (in Python).Adam.Er8– Adam.Er82023年03月08日 13:12:10 +00:00Commented Mar 8, 2023 at 13:12
-
1Have you looked at the included struct module? You can pack data into the struct in one format and unpack it in another.import random– import random2023年03月08日 13:19:18 +00:00Commented Mar 8, 2023 at 13:19
1 Answer 1
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]