C语言中的位移位
int x = 2;
x = rotateInt('L', x, 1); // should return 4
x = rotateInt('R', x, 3); // should return 64
这是代码,有人可以检查一下并让我知道错误是什么吗?
编译成功,但是执行的时候提示SegmentationFault
。
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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
现在就开始磨练您的调试技巧。如果您想成为任何形式的工程师,您将需要编写某种类型的程序,因此您一生都在调试。
开始调试的一个简单方法是放入 print 语句,以查看代码在死亡之前能完成多远。我建议您首先隔离错误。
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
should be
or just
我在我的电脑(MacBookPro / Core2Duo)上尝试过,它工作正常。
顺便问一下,您的目标架构是什么?当您使用 C 运算符“>>”时,某些(许多)处理器执行轮换而不是移位和“<<”。
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|
?