Question

I need to create three bit masks that end up in three 32-bit unsigned ints (let's call them x, y and z). The masks should end up like this:

x: 0000 0001 1111 1111 1111 1111 1111 1111
y: 0000 1110 0000 0000 0000 0000 0000 0000
z: 1111 0000 0000 0000 0000 0000 0000 0000

So far I've got this:

unsigned int x = (1<<25)-1;
unsigned int y = (~x)&((1<<28)-1);
unsigned int z = (~x)<<3;

But it seems a bit messy. Can anyone come up with a more concise (and readable) way?

Was it helpful?

Solution

If you are using C99, use the "new" fixed width types:

uint32_t x, y, z;
x = 0x01FFFFFF;
y = 0x0E000000;
z = 0xF0000000;

Or you could use "ugly" octal :-)

x = 000177777777; // 00 000 001 111 111 111 111 111 111 111 111
y = 001600000000; // 00 001 110 000 000 000 000 000 000 000 000
z = 036000000000; // 11 110 000 000 000 000 000 000 000 000 000

OTHER TIPS

unsigned int x = 0x01FFFFFF,
             y = 0x0E000000,
             z = 0xF0000000;

Is this readable for you?

Simply put into your unsigned int the number you want (if you prefer using hexadecimal notation):

unsigned int mask= 8 ; // 00000000 00000000 00000000 00001000
unsigned int mask = 0x08 ;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top