按位操作以实现向右的逻辑移位 [英] Bit-wise operations to implement logical shift to the right

查看:137
本文介绍了按位操作以实现向右的逻辑移位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在尝试解决此家庭作业,并且我一直困扰着这个特定问题达几个小时,无法解决.我感觉我是如此接近!但是然后我更改了代码中的某些内容,而其他内容则不正确..

So I am trying to solve this home assignment and I have been stuck with this one particular problem for a couple of hours and can't figure it out. I feel like I am so close! But then i change something in the code and something else isn't right..

/*
 * logicalShift - shift x to the right by n, using a logical shift
 *   Can assume that 0 <= n <= 31
 *   Examples: logicalShift(0x87654321,4) = 0x08765432
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 20
 *   Rating: 3
 */
int logicalShift(int x, int n) {

    int move;
    int y;
    y = x >> n;
    y = ~y << 1;
    move = (y & (x >> n));

    return move;
}

这里缺少什么?我将0x80000000 >> 31设置为0,但应该为1-但除此之外,我不知道.

What is missing here? I get 0x80000000 >> 31 as 0 but should be 1 - But other than that I don't know..

推荐答案

C的>>运算符已经对无符号整数执行了逻辑右移.这是您想要的吗?

C's >> operator already performs a logical right shift on an unsigned integer. Does this do what you want?

#include <stdio.h>

unsigned long int logicalShift(unsigned long int x, unsigned int n) {
  return x >> n;
}

int main() {
  unsigned long int value = 0x80000000UL;
  unsigned int shift_amt = 31;
  unsigned long int result = logicalShift(value, shift_amt);
  printf("0x%lx >> %d = 0x%lx\n", value, shift_amt, result);
  return 0;
}

结果:

0x80000000 >> 31 = 0x1

如果您不允许强制转换为无符号数据类型,则根据可能的作业分配进行了修改,以允许除法运算符,替代解决方案也涉及到`x/(1 << n)也是有问题的,因为包含负数的除法舍入也是在C99之前实现定义的.因此,除非您能告诉我们您的讲师正在使用哪个C实现以及它实现哪个ABI,否则这个问题似乎没有简单易行的答案.

If you are not allowed to cast to an unsigned data type, then the result of right shifting a signed value in C is implementation defined, according to this answer by Ronnie which cites K&R Second Edition. Even if this possible homework assignment were amended to allow the division operator, the alternate solution involving an elaboration on `x / (1 << n)' is also problematic because the rounding for division involving a negative number is also implementation-defined prior to C99. So unless you can tell us which C implementation your instructor is using and which ABI it implements, this question would appear to have no answer that is both easy and portable.

这篇关于按位操作以实现向右的逻辑移位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆