0

Problem: I want to generate a Bit mask (uint32_t) based on a given length. Following result should be achieved:

BIT_MASK(3) =  0x00..0111 
BIT_MASK(32) = 0x111..111 

The code given below is working for every length smaller than 32. If the length is 32, the left shift count is larger than the type width (overflow).

#define BIT(n)                  ( 1<<(n) )
#define BIT_MASK(len)           ( BIT(len)-1 )

uint32_t length;
uint32_t mask = BIT_MASK(length);

Question: Is there any other efficient macro solution to generate a Bit mask, which is not including an additional if/else or typecast to avoid that error.

Jacks
  • 67
  • 5

1 Answers1

0

This is pretty much it, but you need to change the literal 1 to 1UL. Otherwise you are restricted to the range of int, which is likely 31 bits instead of 32.

#define BIT_MASK32(n) ( (1UL<<(n)) - 1UL )

Where n must be in the range of 0 to 31 to fit a uint32_t. To safe guard against overflow, you could make it (n)%32, though that will make the macro slower if n is a run-time value rather than an integer constant.

Lundin
  • 195,001
  • 40
  • 254
  • 396