Convert bit sequence to uint32_t in c++

1.3k views Asked by At

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?

2

There are 2 answers

1
Paul R On BEST ANSWER

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
0
Anton Savin On

Another option is

std::uint32_t mask = ~(~0U << n);

Also you have to make sure unsigned int isn't less than 32 bits on your system, it may be better to write

std::uint32_t mask = ~(~(std::uint32_t)0 << n);