问题
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;
}
What is missing here? I get 0x80000000 >> 31
as 0 but should be 1 - But other than that I don't know..
回答1:
0x80000000 >> 31 = 1 if it's a logical shift.
0x80000000 >> 31 = -1 if it's an arithmetic shift.
In C++, if the value being shifted is unsigned, it is logical shift.
In Java, >>
is arithmetic shift. >>>
is logical shift.
回答2:
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;
}
Result:
0x80000000 >> 31 = 0x1
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.
来源:https://stackoverflow.com/questions/25964802/bit-wise-operations-to-implement-logical-shift-to-the-right