tags:

views:

149

answers:

1

Hi there:

I have a question as described: how to perform rotate shift in C without embedded assembly. To be more concrete, how to rotate shift a 32-bit int.

I'm now solving this problem with the help of type long long int, but I think it a little bit ugly and wanna know whether there is a more elegant method.

Kind regards.

+9  A: 

From Wikipedia:

unsigned int _rotl(unsigned int value, int shift) {
    if ((shift &= 31) == 0)
      return value;
    return (value << shift) | (value >> (32 - shift));
}

unsigned int _rotr(unsigned int value, int shift) {
    if ((shift &= 31) == 0)
      return value;
    return (value >> shift) | (value << (32 - shift));
}
Bertrand Marron
If the target has a `rotl` instruction, do you think that the final assembly would use it? If not (which I suspect), I suppose there is no other way than inline assembly?
Gauthier
I don't know whether the wikipedia is right, but when I go over the rotate operation, it seems that some flaws exists if simply perform (value >> shift ) | ( value << ( 32 - shift ) ). NOTICE: the right shift operation in C is signed-extended.
Summer_More_More_Tea
The right shift should only be sign-extended if the variable being shifted is signed. If your 'value' variable is signed, then you'll need to cast it to unsigned for the right shift.
Chris Waters