Rotating bits of any integer in C

Pass the integer 2 to this function, and then return an integer equal to 4

x = 2;
x = rotateInt('L', x, 1); 

(left shift by 1 shift)

Example: 00000010 → turn left by 1 → 00000100

but if I pass this:

x = rotateInt('R', x, 3); 

he will return 64, 01000000

Here is the code, can someone fix 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;   
}
0
source share
6 answers

So, I assume that you know what right and left shifts are. And that you know the difference between arithmetic and logical shifts.

C has only arithmetic shifts. It does not perform logical shifts and does not rotate. ok, i lied, C makes logical shifts on unsigned ints.

, , : , , , , "" .

0010 0001. , 1000. . 1, .

: 0100 1000 0001 0010 ..

, .

, C . , "". , . :

  • . ( 0 1?)
  • - , 1 ( ), , , 1.

.

!

+4

.

, K & R, C, , , - .

unsigned int rightRotateBits(unsigned int inputWord, int numberOfBitsToRotate) {
    int bitWidth = sizeof(inputWord) * 8;
    // Rotating 32 bits on a 32-bit integer is the same as rotating 0 bits;
    //   33 bits -> 1 bit; etc.
    numberOfBitsToRotate = numberOfBitsToRotate % bitWidth;

    unsigned int tempWord = inputWord;

    // Rotate input to the right
    inputWord = inputWord >> numberOfBitsToRotate;

    // Build mask for carried over bits
    tempWord = tempWord << (bitWidth - numberOfBitsToRotate);

    return inputWord | tempWord;
}

-1 -31 bitAmount.

, // //.

+3

Since no one told you how to implement this, you can use intrinsics, for a visual studio they are _rotl, _rotl64, _rotr, _rotr64.

Oh, but rotation and shifts are two different things!

0
source

I recommend using unsigned int.

#define DIR_LEFT 0
#define DIR_RIGHT 1

unsigned int rotateInt(unsigned int in, int amount, byte dir)
{
    return(dir == DIR_RIGHT ? (in >> amount) | ((in & ((0x01 << amount) - 1)) << (sizeof(unsigned int)*8 - amount)) : (in << amount)  | ((in & ~((sizeof(unsigned int)*8*8 - 1) >> amount)));
}
-1
source

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


All Articles