完全公开,这是一个家庭作业问题,我不需要确切的代码。我的任务是在仅使用 ~ & + <<.
的情况下重现以下代码int result = 0;
int i;
for(i = lowbit; i <= highbit; i++)
result |= 1 << i;
return result;
其中 lowbit
和 highbit
是介于 0
和 31
之间的参数。如果 lowbit
比 highbit
大,返回 0。
我试过的是下面的代码
int result = 0;
int negone = ~0x0;
int first = 1 << (lowbit + negone); //the first 1 bit is at the lowbit th location
int last = 1 << (highbit + negone); //the last 1 bit is at the highbit th location
int tick = ~(first + last); //attempting to get all bits in the range of low and highbit.
result = ~(~first & ~tick); //bitwise | without using |
result = ~(~last & ~result);
return result + 1; //the first bit should always be on.
那么我在这里缺少一些基本的东西吗?除了我没有做的事情之外,这也超出了我允许使用的 12 个运算符(operator)的限制,但我想在我开始限制运算符(operator)之前尝试让它工作。
当我对此运行测试脚本时,我在大多数测试中遇到错误,包括 lowbit
和 highbit
彼此相等。 highbit
是最大大小而 lowbit
是最小大小的情况似乎可行。
任何帮助将不胜感激。
最佳答案
negone
应该这样初始化:
uint32_t negone = ~0UL;
您正在添加具有位模式的位数:
int first = 1 << (lowbit + negone); //the first 1 bit is at the lowbit th location
int last = 1 << (highbit + negone);
您应该改为计算 32 位掩码
uint32_t first = negone << lowbit; // all bits below lowbit are 0, others are 1
uint32_t last = negone << highbit << 1; // all bits above highbit are 1, other are 0
结果是用last
屏蔽first
的补码得到的:
uint32_t result = ~first & last;
结合上述步骤给出了一个直接的解决方案,有 7 个运算符(12 个包括括号和赋值),没有加法,也没有减法:
uint32_t result = ~(~0UL << highbit << 1) & (~0UL << lowbit);
我使用 0UL
因为类型 unsigned long
保证至少有 32 位,而类型 unsigned int
可能只有 16 位。
关于c - 如果该位介于低和高之间,则将 0 位变为 1 位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41924540/