开发者

Is there a concise way to create bit masks in C?

I need to create开发者_StackOverflow 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?


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

Is this readable for you?


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


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 ;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜