在C中的参数给定范围内的屏蔽位 [英] Masking bits within a range given in parameter in C
问题描述
我是C语言编程的新手,不能确定是否已有很好的解释,如果可以的话,对不起.我正在尝试将位设置在给我的范围内.函数签名看起来像:
I am new to C programming and not sure that there is already a good explanation for how to do this, if so I am sorry. I am trying to set the bits within a range given to me. the function signature looks like:
unsigned int setBits(int low, int high, unsigned int source) {
source
是要操作的数字,low
是该范围内的最低位,而high
是该范围内的最高位.我了解在尝试具体获取最后4位或前4位或其任意组合时的位移很好,但不了解如何从将在参数中更改的范围中获取位.任何帮助将不胜感激.
source
being the number to be operated on, low
being the lowest bit in the range, and high
being the highest bit in the range. I understand bit-shifting just fine when trying to get specifically the last 4 bits or first 4 or any combination thereof, but do not understand how to get the bits from a range that will be changed in the parameter. Any help would be greatly appreciated.
推荐答案
2种方法:将source
中的位从low
设置为high
的迭代方法:
2 approaches: Iterative method to set bit in source
from low
to high
:
unsigned int setBitsI(int low, int high, unsigned int source) {
while (low <= high) {
source |= 1u << low;
low++;
}
return source;
}
非迭代方法:
unsigned int setBitsNI(int low, int high, unsigned int source) {
unsigned setmask = 1u << (high - low);
setmask <<= 1;
setmask--;
setmask <<= low;
return source | setmask;
}
当high
为"bit-width-1"且low
为0,1u << bit_width
为UB时,避免使用1u << (1u + high - low)
十分重要.
Important to avoid 1u << (1u + high - low)
for when high
is "bit-width-1" and low
is 0, 1u << bit_width
is UB.
low
或high
的值应超出位范围,否则会出现问题.
Should low
or high
have an value outside the bit range, problems occur.
这篇关于在C中的参数给定范围内的屏蔽位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!