【问题标题】:Homework Help(Bit manipulation)作业帮助(位操作)
【发布时间】:2017-02-24 23:10:25
【问题描述】:

我对位操作相当陌生,所以如果你能帮助我,那就太好了!我明白 (&,|, ~ , ^) 当你比较两个不同的字节时会做什么。我也明白 (>) 就像除以 2^i 位。我已经尝试过了,但我认为有更好的方法。

问题来了:

编写一个函数,将整数中的特定位数设置为 1,将所有其他位设置为 0。该值应从函数返回。例如,当整数 x = 3 和 y = 8 传递给函数时,函数应返回二进制数为 00000000 00000000 00000111 11111000 的整数。也就是说,将位从第 3 位转换为第 11 位 (3+8)为 1,其他为 0。 提示:这个函数有两个参数:一个起始位数和从起始位开始计数的位数。应该使用按位加法和移位。

这是我目前所拥有的:

int function(int startBit, int numBits){
   int num = 0;
   int num1 = 1;
   int i;

   for(i = startBit; i < startBit+numBits; i++){
          num = num | num1 << i;

   }
   return num;
}

提前致谢!

【问题讨论】:

    标签: c bit-manipulation


    【解决方案1】:

    这个解决方案有点慢,但符合要求:

    // First, create the number of 1 bits needed
    int result = 0;
    for (i = 0; i < numBits; ++i)
      result = (result << 1) + 1;
    
    // Then shift the 1 bits to the correct position
    result <<= startBit;
    

    【讨论】:

      【解决方案2】:

      这方面的常见问题是:

      ((1 << numBits) - 1) << startBit
      

      但我不确定这是否满足您的“应使用按位加法和移位”限制。

      【讨论】:

      • 当 (1 INT_MAX 它的值将换行。 OP 的示例是 64 位,因此仅当 numBits
      • 是的,您绝对必须注意数据类型以及 numBits 和 startBit 的值,否则您将得到错误的结果。这些类型的位旋转有很多,它们通常用于硬件控制寄存器的上下文中,其中 numBits 和 startBit 的值是常量,并且其值使得结果定义明确。
      猜你喜欢
      • 2011-08-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-17
      相关资源
      最近更新 更多