c - 如果该位介于低和高之间,则将 0 位变为 1 位

标签 c bitwise-operators bit-shift

完全公开,这是一个家庭作业问题,我不需要确切的代码。我的任务是在仅使用 ~ & + <<.

的情况下重现以下代码
int result = 0;
int i;
for(i = lowbit; i <= highbit; i++)
    result |= 1 << i;
return result;

其中 lowbithighbit 是介于 031 之间的参数。如果 lowbithighbit 大,返回 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)之前尝试让它工作。

当我对此运行测试脚本时,我在大多数测试中遇到错误,包括 lowbithighbit 彼此相等。 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/

相关文章:

c - 如何重置指针

C 代码错误 以前从未见过

javascript - 如果其大小大于 32 位,如何将二进制数据(水平方向) “rotate”?

haskell - 将位转换为 Int8 Haskell

c# - Bitshifting Int16 仅适用于文字

c - 从二维数组中删除最大和最小数字而不进行排序

C:动态初始化一个常量字符串数组

java - 没有异或的按位交换

c - 将 32 位整数与自身异或

programming-languages - Go 语言中的 >> 是什么意思?