C 中带有 0 的位掩码

  • 本文关键字:掩码 c bitmask
  • 更新时间 :
  • 英文 :


我需要用 C 构建一个返回 int 的方法,以 3 个整数作为参数。第一个和第二个 int 是起始位和结束位位置。第三个 int 是 0 或 1,用于确定掩码的类型。

例如

getMask(2, 6, 1); 
//Set bits 2 to 6 to 1, set all others to zero

应将位 2 到 6 设置为 1,将所有其他位设置为零。

0 0  0  0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0

所以getMask(2, 6, 1)应该返回整数 124。

getMask(11, 31, 0)(将位 11 设置为 31 到 0)应返回 2047。

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1

这是我目前拥有的:

#include <stdio.h>
int getM(int start, int end, int choice) {
if (choice == 1){
return ~(~0 << (end - start + 1)) << (start);
}
else if (choice == 0){
return ~(~1 << (end - start + 1)) << (start);
}
else{
return 0;
}
}

当我的选择是 1 时它有效,但对于 0,我完全迷失了。

我目前得到 -2048 的 getMask(11, 31, 0)。

我知道我可以使用 ands 和 ors,但我无法弄清楚如何以我的方式使用它们。

@AnttiHaapala是正确的:choice==0只是对相同startendchoice==1的按位否定。 因此(作为MCVE):

#include <stdio.h>
int getM(int start, int end, int choice) {
if (choice == 1){
return ~(~0 << (end - start + 1)) << (start);
}
else if (choice == 0){
return ~getM(start, end, 1); /* Just use what you have, but ~ it */
}
else{
return 0;
}
}
int main() {
printf("2 6 1 %dn", getM(2,6,1));
printf("11 31 0 %dn", getM(11,31,0));
}

最新更新