简体   繁体   English

从字节中提取和拼接位

[英]Extracting and splicing Bits from Byte

I have a processor that stores three 10 bit words in the following way - bits 0-7 are in a one byte word, but bits 8 and 9 are combined with bits 8 and 9 from the other three registers into a single word. 我有一个以以下方式存储三个10位字的处理器-0-7位在一个字节字中,但是位8和9与来自其他三个寄存器的位8和9组合成一个字。 It looks like this: 看起来像这样:

1) XXAABBCC 2) AAAAAAAA 3) BBBBBBBB 4) CCCCCCCC 1)XXAABBCC 2)AAAAAAAA 3)BBBBBBBB 4)CCCCCCCC

So I need to grab two bits from word 1 and then put them at the front of the respective words 2, 3 or 4. How do I extract the embedded bits in word 1, and how do I join them to the other 8 bits? 因此,我需要从单词1中抓取两个位,然后将它们放在相应的单词2、3或4的前面。如何提取单词1中的嵌入位,以及如何将它们与其他8位连接起来?

Depending on where the bits are stored, there will be a corresponding bit pattern that has all (binary) ones in those locations, and zeroes elsewhere. 根据位的存储位置,将有一个相应的位模式 ,在这些位置中所有(二进制)为1,而在其他位置为零。 Find out that bit pattern, or a formula for that bit pattern. 找出该位模式或该位模式的公式。

For example, if the two bits are next to each other, and are in the layout you displayed, the bit patterns might be A: 0x30, B: 0xC0, C: 0x03. 例如,如果两个位彼此相邻,并且在您显示的布局中,则位模式可能是A:0x30,B:0xC0,C:0x03。

Keeping the same indexes you showed, you have 1 -> 0x30, 2 -> 0xC0, 3 -> 0x03. 保持显示的相同索引,您将获得1-> 0x30、2-> 0xC0、3-> 0x03。 Since there are two bits in the pattern, you can multiply by two: 2 -> 0x30, 4 -> 0xC0, 6 -> 0x03, which makes the formula something like 0xC0 >> (2*i) where i is the index. 由于模式中有两位,因此可以乘以2:2-> 0x30,4-> 0xC0,6-> 0x03,这使公式类似于0xC0 >> (2*i) ,其中i是索引。

A function might look like: 一个函数可能看起来像:

def extract_10bit_word(code_bytes, i):
    """Extract 10-bit word 'i' from 4-byte package code_bytes, where 
    words are encoded as 2-bit packets (high bits) in byte 0, plus
    8-bit bytes in byte i, which must be [1,3]."""

    assert i in range(1, 4)
    assert len(code_bytes) == 4

    hi_bits = code_bytes[0] & (0xC0 >> (2 * i))
    return (hi_bits << 8) | code_bytes[i]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM