Bit Offset 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 tell me what the error is?

The compilation is successful, but it says Segmentation Faultwhen 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;   
 }
+3
source share
4 answers

I tried on my computer (MacBookPro / Core2Duo) and it worked. By the way, what is your target architecture? Some (many) processors rotate instead of shifts when you use the C "→" and "<" operators.

+1
source

Start honing your debugging skills now. If you become an engineer of any form, you will need to write programs of some variety and, thus, debug your whole life.

, , . .

+9

Not sure about seg error, but I think

if((x & 128) == 1)  

it should be

if((x & 128) == 128)

or simply

if(x & 128)  
+2
source

When you use ^, you do not mean the operator or operator |?

0
source

Source: https://habr.com/ru/post/1769449/


All Articles