Interleave Bytearrays #9857
Answered
by
dlech
A622266
asked this question in
Hardware & Peripherals
Interleave Bytearrays
#9857
-
I want to interleave two bytearrays. Since the bytes represent 16-bit numbers, I need to interleave on a 2-byte boundary. Example
How can this be done in |
Beta Was this translation helpful? Give feedback.
Answered by
dlech
Nov 6, 2022
Replies: 1 comment 5 replies
-
One way could be to use a generator function: def interleave(a, b):
ia = iter(a)
ib = iter(b)
while True:
try:
yield next(ia)
yield next(ia)
yield next(ib)
yield next(ib)
except StopIteration:
return
bytearray3 = bytearray(interleave([1, 1, 2 , 2], [3, 3, 4, 4])) Or since you are working with 16-bit values, you could use from array import array
a1 = array('H', [0x0101, 0x0202])
a2 = array('H', [0x0303, 0x0404])
a3 = array('H')
for n1, n2 in zip(a1, a2):
a3.append(n1)
a3.append(n2) |
Beta Was this translation helpful? Give feedback.
5 replies
Answer selected by
A622266
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
One way could be to use a generator function:
Or since you are working with 16-bit values, you could use
array
instead if it is available.