Python 将 8 位分配到 4 x 8 位的开头,两两分配

Python distribute 8 bits into beginnings of 4 x 8 bits, two by two

我有一个 8 位整数,我想将这些位两两分配到 4 个整数(4x8 位)的开头。例如:

bit_8 = 0b_10_11_00_11
bit_32 = b"\x12\x32\x23" # --> [0b100_10, 0b1100_10, 0b1000_11, 0b1011_00]

what_i_want = [0b100_10, 0b1100_11, 0b1000_00, 0b1011_11]

为了便于阅读,我在列表中写了数字,但我希望它们是 bytes。我不太擅长位操作,也找不到好的方法。 我会多次重复这个过程,所以我需要一个快速的解决方案。我在 here 找到了一种逐位设置的方法,但我想知道是否有更好的方法来解决我的问题。

语言没那么重要,我需要算法。不过我更喜欢Python.

您可以通过在 bit_32 上反向迭代,同时取 bit_8 的最后两位,然后将其右移来实现。 这样,您可以按相反顺序构建输出值列表,您可以在转换为字节时重新排序。

bit_8 = 0b_10_11_00_11
bit_32 = b"\x12\x32\x23" # --> [0b100_10, 0b1100_10, 0b1000_11, 0b1011_00]

what_i_want = [0b100_10, 0b1100_11, 0b1000_00, 0b1011_11]

out_lst = []
for b in reversed(bit_32):
    bits_from_bit_8 = bit_8 & 0b11  # last two bits of bit_8
    bit_8 >>= 2  # we shift it right by to bits 
    out_lst.append(b & 0b11111100 | bits_from_bit_8) 
out = bytes(reversed(out_lst))

print(out)
#b'\x123 /'

# Check that this is the expected output:
print([i for i in out], what_i_want)
# [18, 51, 32, 47] [18, 51, 32, 47]