3

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?

4

3 回答 3

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

这对你来说可读吗?

于 2011-09-12T09:06:28.103 回答
4

如果您使用的是 C99,请使用“新”固定宽度类型:

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

或者你可以使用“丑陋”的八进制:-)

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
于 2011-09-12T09:07:53.987 回答
2

只需将所需的数字放入您的 unsigned int 中(如果您更喜欢使用十六进制表示法):

unsigned int mask= 8 ; // 00000000 00000000 00000000 00001000
unsigned int mask = 0x08 ;
于 2011-09-12T09:07:26.117 回答