Search code examples
c++maskbitset

Can this bitset generation be made better or more efficient?


Problem: Given an integer led as input, create a bitset (16 bits) with led bits set to 1. Then, create the following sequence (assume in this case led = 7):

0000000001111111
0000000000111111
0000000001011111
0000000001101111
0000000001110111
0000000001111011
0000000001111101
0000000001111110

Note that it is a "zero" that is moving to the right. The code I wrote is:

void create_mask(int led){
    string bitString;
    for (int i = 0; i < led; i++){
        bitString += "1";
    }
    bitset<16> bitMap(bitString);

    for (int i = led; i >= 0; i--){
        bitMap[i] = false;
        cout << bitMap << endl;
        bitString = "";
        for (int j = 0; j < led; j++){
            bitString += "1";
        }
        bitMap = bitset<16> (bitString);
    }
}

I don't like the nested loop where I set each bit to 0. I think that could be made better with less complexity.


Solution

  • This is what I came up with:

    void createMask(int len) {
        std::bitset<16> bitMap;
        for (int i = 1; i < len; i++)
        {
            bitMap.set();
            bitMap >>= 16 - len;
            bitMap[len - i] = false;
            std::cout << bitMap << std::endl;
        }
    }
    

    bitMap.set() sets all bits in the bitset to 1 (or true) bitMap >>= 16 - len shifts all the bits to the right but it does it 16 - 7 (if len was 7) so there are 9 zeros and seven ones. bitMap[len - i] = false sets the bit at 7 - i to 0 (or false). len - i is a way of specifying the inverse number (basically it starts setting the zeros on the left and works towards the right depending on the value of i) The loop starts at 1 because you're setting the bit to 0 anyways and prevents program from crashing when len is 16 –