C wrong answer of circular shift of a number

3

The implementation of the right shift is:

unsigned int rotr(unsigned int value, int shift) {
    return (value >> shift) | (value << (sizeof(value) * 8 - shift));
}

but if value is 0x17=00010111 that result should be 0x8b=10001011 but the result is 0x8000000b.

how to handle this problem?

#include <stdio.h>
unsigned int rotr(unsigned int value,int shift) {
    return (value >> shift) | (value << (sizeof(value) * 8 - shift));
}
int main()
{
  unsigned int a = 0x17;
  printf("%x",rotr(a,(unsigned)1));
}

=> 8000000b
c
bit-manipulation
shift
asked on Stack Overflow Dec 23, 2013 by Pooya

1 Answer

5

This is the correct result of rotating 0x17 in a 32-bit integer: you start with

00000000 00000000 00000000 00010111

and you end up with

10000000 00000000 00000000 00001011

If you would like to rotate an 8-bit number, use uint8_t instead of int as the function parameter:

uint8_t rotr(uint8_t value, int shift) {
    // No need to multiply by sizeof(value), because the type uint8_t forces it to be 1
    return (value >> shift) | (value << 8 - shift));
}
answered on Stack Overflow Dec 23, 2013 by Sergey Kalinichenko

User contributions licensed under CC BY-SA 3.0