Home > OS >  Left rotate number by N bits
Left rotate number by N bits

Time:12-30

Suppose I have this number eg: 11 which in base 2 is represented as : 1011 . I want to left rotate by N bits this number. So if N = 5 (0101) , then 1011 left rotated by 5 should be 0111 = 7 . Also ,numbers should always be represented on 4 bits.

I tried this approach but can't figure out what the SIZE should be. If I set SIZE to 8 its output will be 353 which is not what I intended.

unsigned int op_lrotate(unsigned int nr1 , unsigned int nr2){
    return (nr1 << nr2)|(nr1 >> (SIZE - nr2));

}
int main(){
  unsigned int nr1=11;
  unsigned int nr2=5;
  unsigned int result = op_lrotate(nr1,nr2);
  printf("%u",result);
}

CodePudding user response:

This doesn't work as you aren't accounting for the size of the variable correctly (where if it happened to somehow be a uint4_t (if such a type existed) the excess bits would have been shifted out). Since you're rotating the value logically sized SIZE, you need to base your shifts on nr2 % SIZE and mask off the result accordingly.

For standard sized types, I'd suggest you look at this answer for rotate best practices.

In the specific case, see the example below, but note that SIZE must be <= the number of bits in the shifted type or undefined behavior will occur (hence the assert).

#include <limits.h>

#define SIZE (4)

unsigned int op_lrotate(unsigned int nr1, unsigned int nr2){
    unsigned int shift = nr2 % SIZE;
    unsigned int result;
    assert(SIZE <= (CHAR_BIT * sizeof(nr1)));
    if (!shift)
    {
        return nr1;
    }
    result = (nr1 << shift) | (nr1 >> (SIZE - shift));
    result &= (~0U >> (CHAR_BIT * sizeof(nr1) - SIZE));
    return result;
}
  • Related