bit shifting in C
int x = 2;
x = rotateInt('L', x, 1); // should return 4
x = rotateInt('R', x, 3); // should return 64
Here is the code, can someone check it and let me know what the error is?
Compilation is successful, but it says Segmentation Fault
when I execute it.
int rotateInt(char direction, unsigned int x, int y)
{
int i;
for(i = 0; i < y; i++)
{
if(direction == 'R')
{
if((x & 1) 开发者_运维知识库== 1)
{
x = x >> 1;
x = (x ^ 128);
}
else
x = x >> 1;
}
else if(direction == 'L')
{
if((x & 128) == 1)
{
x = x << 1;
x = (x ^ 1);
}
else
x = x << 1;
}
}
return x;
}
Start honing your debugging skills now. If you are going to be any form of an engineer, you'll need to write programs of some variety, and will thus be debugging all of your life.
A simple way to start debugging is to put print statements in to see how far your code makes it before it dies. I recommend you start by isolating the error.
Not sure about the seg fault, but I think
if((x & 128) == 1)
should be
if((x & 128) == 128)
or just
if(x & 128)
I tried on my computer (MacBookPro / Core2Duo) and it worked. By the way, what's your target architecture ? Some (many) processors perform rotation instead of shifts when you use the C operators ">>" and "<<".
When you use ^
don't you mean the or operator |
?
精彩评论