Search code examples
c++c++11bitmaskbit-manipulation

Generate Bitmask


Given two integers; size and offset, how would I go about generating a bitmask with the following properties;

MSD             LSD
1111 1111 0000 1111
          ^  ^
size = 4 -|  |
             |  
offset = 4  -|

Solution

  • Since the question is tagged as c++, I'm going to provide an STL based solution:

    bitset<NUM_BITS> bs(0);
    bs = ((bs.flip() << size).flip() << offset).flip();
    

    Same code split into several lines:

    bitset<NUM_BITS> bs(0);
    bs.flip();
    bs <<= size;
    bs.flip();
    bs <<= offset;
    bs.flip();
    

    Performance considerations are up to the readers.