问题描述
如何设置(最优雅的方式) n 最低有效位 uint32_t ?这是写一个函数 void setbits(uint32_t * x,int n); 。函数应处理 0 到 32 的每个 n / p>
特别是应该处理 n == 32 。
如果你的意思是最低有效的n位:
((uint32_t) 1<< n) - 1
在大多数架构上, 32,所以你可能需要做一个特殊的情况下:
n == 32? 0xffffffff:(1
在64位架构上,可能)更快的解决方案是:然后下来:
(uint32_t)((uint64_t)1< - 1)
事实上,这在32位架构上甚至可能更快, 。
How to set (in most elegant way) exactly n least significant bits of uint32_t? That is to write a function void setbits(uint32_t *x, int n);. Function should handle each n from 0 to 32.
Especially value n==32 should be handled.
If you meant the least-significant n bits:
((uint32_t)1 << n) - 1
On most architectures, this won't work if n is 32, so you may have to make a special case for that:
n == 32 ? 0xffffffff : (1 << n) - 1
On a 64-bit architecture, a (probably) faster solution is to cast up then down:
(uint32_t)(((uint64_t)1 << n) - 1)
In fact, this might even be faster on a 32-bit architecture since it avoids branching.
这篇关于在unsigned int中设置最后的n个位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!