2

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?

Paul R
  • 208,748
  • 37
  • 389
  • 560
Illania
  • 117
  • 1
  • 1
  • 14

2 Answers2

7

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
Paul R
  • 208,748
  • 37
  • 389
  • 560
2

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);
Anton Savin
  • 40,838
  • 8
  • 54
  • 90