/*
logicalShift - shift x to the right by n, using a logical shift
can assume that 0<= n <=31
Examples: logicalShift(0x87654321,4) = 0x08675432
Legal ops: ! ~ & ^ | + << >>
Max ops: 20
Rating: 3 */
int logicalShift(int x, int n) {
return 0;
}
How would I code the logicalShift in C?
I have this, but this isn't right. I think I'm in the right track though:
int logicalShift(int x, int n) {
int a = ~0;
int shift = 31 + ((~n)+1);
a=a<<shift;
a=~a;
x=x>>n;
return x & a;
}
int right_logical_shift(int num, int n){
int size_int = 8 * sizeof(int); // Calculating size of int in bits
so as to create a bit mask for getting sign bit
int mask = 1<<(size_int - 1); // Creating a mask of the form
0x80000000 (32 bit int)
int sign_bit = (mask&num) == 0?0:1; // Sign bit = 0 if positive
number else sign bit = 1
int num_without_sign = num&(~mask); // Removing sign bit from
the number ~mask = 0x7FFFFFFF (32 bit int)
num_without_sign>>=n; // Right shift number without sign by n
bits
sign_bit <<=(size_int - 1 - n); // Now left shift sign bit
(which is either 0 or 1) by size of int - n - 1
num = (sign_bit|num_without_sign); // Logical And operation of sign
bit and number without sign gives the
// number logically shifted by n bits
return num;
}
Get Answers For Free
Most questions answered within 1 hours.