Search code examples
c++binarybit-manipulationbitwise-operatorsuint32

Convert bit sequence to uint32_t in c++


User specifies register (LFSR) length with integer as a parameter for a function, for example he enters number 5. I need to initialize this 5-bit length LFSR with all 1 bits (for length 5 it will be 11111) and get a seed mask in a format uint32_t - for 5-length register it will be 0x0001f.

What is the best way to get mask 0x0001f for 5 bit length register when a user enters only length of the register as an integer number 5?


Solution

  • To generate a mask of n bits (where n < 32):

    uint32_t mask = (1U << n) - 1U;
    

    Explanation: consider the example where n = 5:

    1U << n = 1U << 5 = 0000 0000 0000 0000 0000 0000 0010 0000 = 0x20
    

    then we subtract 1 and get:

                        0000 0000 0000 0000 0000 0000 0001 1111 = 0x1f