简体   繁体   English

C中的位移位

[英]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. 编译成功,但在执行时会显示Segmentation Fault

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. 开始调试的一种简单方法是将print语句放入其中,以查看代码在其消失之前的程度。 I recommend you start by isolating the error. 我建议你先从错误中分离出来。

Not sure about the seg fault, but I think 不确定seg故障,但我认为

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. 我试过我的电脑(MacBookPro / Core2Duo)并且它有效。 By the way, what's your target architecture ? 顺便问一下,你的目标架构是什么? Some (many) processors perform rotation instead of shifts when you use the C operators ">>" and "<<". 当您使用C运算符“>>”和“<<”时,一些(许多)处理器执行旋转而不是移位。

When you use ^ don't you mean the or operator | 当你使用^时,你不是指或运算符| ?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM