cbit-manipulationgameboy

Bits: Search&Replace bit sequences


Being a high-level programmer myself, I struggle a lot with bitwise operations. I hope what I'm trying to achieve is doable?

Let's say I have one unsigned 8-bits integer - it can be any value. Let's work on two examples: 0xe4 (11100100) and 0xa5 (10100101).

The hardware interprets those as 4 chunks: 11 10 01 00 and 10 10 01 01.

I'm trying to write 3 methods in pure C:

Tried to search for bit-replacing methods, but couldn't bend any to solve this particular requirement. Where should I start?


Solution

  • Here are some fast, non-looping one-liners that do what you want:

    unsigned set_00_to_01(unsigned x) {
        return x + ((~x >> 1) & ~x & 0x55);
    }
    
    unsigned set_01_to_10(unsigned x) {
        return x + ((~x >> 1) & x & 0x55);
    }
    
    unsigned set_10_to_11(unsigned x) {
        return x + ((x >> 1) & ~x & 0x55);
    }
    

    Note that they only operate on the low-order 8 bits, but they could easily be changed to operate on more by changing the 0x55 values to 0x5555 or 0x55555555 for instance.

    Each function is hard-wired to its specific task, so you can't pass in arbitrary values. Their main advantage is their speed.