So after many hours of mulling this over and now missing several hairs that used to populate my head, I decided to seek outside help.
In my introduction to computer systems class, we have been tasked to do things that are built into the language without using them. I understand that its an exercise of the mind, and not really a useful implementation, but I'm stuck on the logical shift left. The '>>' operator does arithmetic shift left.I am not allowed to cast anything, so changing the ints to unsigned isn't allowed.
I'm using emacs on Ubuntu 10.1.something, if this changes anything.
given info:
logicalShift - shift x to the right by n, using a logical shift
Can assume that 1 <= n <= 31
Examples: logicalShift(0x87654321,4) = 0x08765432
Legal ops: ~ & ^ | + << >>
Max ops: 16
My attempt at the solution:
int
logicalShift(int x, int n) {
int z = ~x+1; /* 2's complement*/
int q = z>>n;
int result= q;
return result;
}
this works for positive ints, but not negative ints (keep in mind that they are signed integers). I could do it easily if I could find a way to make a number (in binary) with n 1's followed by 32-n 0's, but I'm not allowed to multiply, and I can't think of another way. Any hints would be greatly appreciated.