bit-manipulationbit

Bit manipulation in a range


While I know the process to set/unset a bit at a specific location - what is the most efficient way to do this operation over a range (say from position x to y)?

101011011011

n=12
x=3,y=7(from right)

Bit set: 101011111111
Bit unset: 101010000011

The mask has to be pushed dynamically as x and y will obviously be random.


Solution

  • Are we talking about C-like operations? If you want x and y to be variables, you can build two masks:

    unsigned set(unsigned val, int x, int y) {
      unsigned hi = ~0 << x;    // 1's at position x and higher
      unsigned lo = ~(~0 << y); // 1's at positions lower than y
      return val | (lo & hi);
    }
    

    and

    unsigned clear(unsigned val, int x, int y) {
      unsigned hi = ~(~0 << x);   
      unsigned lo = ~0 << y; 
      return val & (lo | hi);
    }
    

    Note the end of the range is non-inclusive at the high end. So set(foo, 5, 9) sets bits 5 through 8, where each bit i is the one with value 2^i.