cbit-manipulationbitwise-operatorsbit-shift

Unexpected output from right rotate function


I was trying to solve the exercise that says

Exercise 2-7. Write the function rightrot(b, n) which rotates the integer b to the right by n bit positions.

and i did code it, here is the code

#include <stdio.h>

int rightrot(int b, int n) {
    char i = 1;

    while (n > 0) {
        if ((b & i) == i) {
            b = b >> 1;
            b = b << 25;
            b = ~b;
            b = b >> 1;
            b = ~b;
            b = b >> 24;
        }
        else
            b = b >> 1;
        n--;
    }

    return b;
}

int main() {
    int i, j, k;

    printf("Enter number: ");
    scanf("%d", &i);
    printf("Enter rotation: ");
    scanf("%d", &j);
    
    k = rightrot(i, j);
    printf("%d\n", k);
    return 0;
}

inputs and output are

Enter number: 153
Enter rotation: 3
-13

153 in binary is 00000000000000000000000010011001, so when it goes in while loop inside while it goes in if for first time (when n is 3), and as you see inside if there are 6 lines of code with bitwise operators to manipulate b and this is what i think how those 6 lines should change b

00000000000000000000000001001100
10011000000000000000000000000000
01100111111111111111111111111111
00110011111111111111111111111111
11001100000000000000000000000000
00000000000000000000000011001100

and then n is 2 and then other 2 while loops should go through else that i wont explain as if's 6 lines code itself doesn't work as i want them too, i know it because i tested them separately.

Also all that is for i am rotating binary as its 8 bit not 32 bit.

Final output should be 51, and i am using arch linux which is 64 bit fully updated, terminal is st by suckless, text editor is vim, i compiled the code using "gcc main.c -o main".


Solution

  • Final output should be 51

    Achievable when unsigned math is used for b.

    // int rightrot(int b, int n) {
    int rightrot(unsigned b, int n) {
    

    Code like b = b >> 24; does a sign extended shift right when perhaps a logical shift right is desired.