Pass a integer 2 to this function and then return a integer which is 4
x = 2;
x = rotateInt('L', x, 1);
(left shift the bits by 1)
Example: 00000010 -> rotate left by 1 -> 00000100
but if I pass this:
x = rotateInt('R', x, 3);
it will return 64, 01000000
Here is the code, can someone correct the error... thanks
int rotateInt(char direction, unsigned int x, int y)
{
unsigned int mask = 0;
int num = 0, result = 0;
int i;
for (i = 0; i < y; i++)
{
if (direction == 'R')
{
if ((x & 1) == 1)
x = (x ^ 129);
else
x = x >> 1;
}
else if (direction == 'L')
{
if ((x & 128) == 1)
x = (x ^ 129);
else
x = x << 1;
}
}
result = (result ^ x);
return result;
}
So, I'll assume you know what right and left shifts are. And that you know the difference between arithmetic and logical shifts.
C only has arithmetic shifts. It doesn't do logical shifts, nor does it do rotates. okay I lied, C does logical shifts on unsigned ints.
A rotate does, well, exactly that: it's the same as a logical shift, except when you shift past the end of the number, the digits "wrap around" to the other side. For example
0010
right-rotated is0001
. If you right-rotate again, you get1000
. See, the1
wrapped around, or rotated, to the other side of the integer.The left rotate is similar:
0100
left rotate1000
left rotate0001
left rotate0010
etc.Note that rotates don't keep the sign bit as an arithmetic right-shift would.
So, C only has arithmetic shifts. So you have to implement the "rotate" part manually. So, take a left-rotate. You would want to:
You should be able to figure out a similar method for right rotates.
good luck!
It seems like your rotate to the right is RIGHT. 1 fell of the side and returned back again from the left?
Anyway, here are your ingredients:
http://tigcc.ticalc.org/doc/keywords.html#if - for determining if it is 'L' or 'R'
http://tigcc.ticalc.org/doc/keywords.html#for - for counting number of times to shift
and
http://msdn.microsoft.com/en-us/library/f96c63ed(VS.80).aspx - to actually shift it
Go, play with it. It WILL work eventually!
Since no one told you how to implement this, you can use intrinsics, for visual studio they are _rotl, _rotl64, _rotr, _rotr64.
Oh, but rotation and shifts are 2 different things!
I recommend using an
unsigned int
.Have a look at the bitwise shift operators:
http://en.wikipedia.org/wiki/Bitwise_operators#Shifts_in_C.2C_C.2B.2B_and_Java
The accepted answer is very nice and straight-forward.
However, I was doing some K&R exercises to refresh my C, and wanted to share this rotate-to-the-right function which may come in handy for people trying to learn bit-wise operations.
For left-rotations just pass values between -1 and -31 to the
bitAmount
argument.Do note that this function favors teachability/legibility/simplicity over efficiency/portability/compactness.