How does the rotation of bits in C work?


I would like to know how the bit rotation works, because the content that I could find on the internet does not explain for sure.

Note: The structure is as follows:

unsigned _rotl(unsigned valor,int conta); // deslocamento para a esquerda
unsigned _rotr(unsigned valor,int conta); // deslocamento para a direita

Since account represents the number of times to rotate.

asked by anonymous 17.03.2014 / 00:08

3 answers


Bit rotation is similar to the bit shift process. However, in this case you do not "lose" the bits that extrapolate the size of your variable (most significant or least significant, depending on the direction of rotation). These bits are repositioned at the opposite end. That is, the most significant becomes the least significant or the opposite if the rotation is in the opposite direction. This image illustrates well.

For example:

Assuming valor is:

valor = 1; // 0001  usando 4 bits para exemplo.

If you rotate this value to the right:

O 1 foi para o início.
1000 // 1 vez
0100 // 2 vezes
0010 // 3 vezes
0001 // 4 vezes

If you rotate this value to the left:

0010  // 1 vez
0100  // 2 vezes
1000  // 3 vezes

This is the pure bit offset because, comparing with the rotation to the right in the first case, if you shift right once the result would be zero, because it would add a zero where it was 1.

17.03.2014 / 00:27

This Wikipedia text ( Circular Shift - Circular Change, in free translation ) explains how this is done.


A circular shift is the operation of rearranging the entries in a tuple, or moving from the final entry to the first position, while switching all the other entries to the next position, or performing the inverse operation. A circular shift is a special type of cycle , which in turn is a special type of permutation.

The image below illustrates this.




To the right the result would be:

If the 0001 0111 bit sequence has been subjected to a circular change of 3 bit positions:

  • To the left is: 1011 1000 .
  • To the right it is: 1110 0010 .
17.03.2014 / 00:41

Running 8 bits to the left
01110000 %

Running 8 bits to the right
11000001 %

17.03.2014 / 00:25