如何缩短以下C片段? 基本上,给定一个整数X,我想设置X多位。
for(i=0;i<NUM; i++){
u32Mask |= (0x1 << i);
}
答案 0 :(得分:2)
if(i == 32) // X86 ignores shift count of 32
u32mask = 0xffffffffu;
else
u32mask = (1u << i) - 1;
或由BeeOnRope评论
uint32_t tbl[33] =
{0x00000000u,0x00000001u,0x00000003u,0x00000007u,
0x0000000fu,0x0000001fu,0x0000003fu,0x0000007fu,
0x000000ffu,0x000001ffu,0x000003ffu,0x000007ffu,
0x00000fffu,0x00001fffu,0x00003fffu,0x00007fffu,
0x0000ffffu,0x0001ffffu,0x0003ffffu,0x0007ffffu,
0x000fffffu,0x001fffffu,0x003fffffu,0x007fffffu,
0x00ffffffu,0x01ffffffu,0x03ffffffu,0x07ffffffu,
0x0fffffffu,0x1fffffffu,0x3fffffffu,0x7fffffffu,
0xffffffff};
// ...
u32mask = tbl[i];