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