简体   繁体   中英

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. It looks like this:

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?

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. 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.

Keeping the same indexes you showed, you have 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.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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