Rotating bits of any integer in C

Posted by Tim on Stack Overflow See other posts from Stack Overflow or by Tim
Published on 2010-10-13T22:45:36Z Indexed on 2011/01/05 0:54 UTC
Read the original article Hit count: 117

Filed under:
|
|
|
|

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;   

}

© Stack Overflow or respective owner

Related posts about c

    Related posts about homework