How does the rotation of Bits in C work?

Asked

Viewed 2,325 times

10

I would like to know how the bit rotation works, because the content I was able to 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

Where the account represents the number of times to rotate.

3 answers

8


The bit rotation is similar to the bit displacement process. Only, in this case, you don’t "lose" the bits that extrapolate the dimension of your variable (the most significant or the least significant, depending on the direction of the 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. That one picture illustrates well.

For example:

Supposing valor be it:

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

If you rotate this value to the right:

O 1 foi para o início.
v
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 defers to the pure bit offset because, comparing to the right rotation in the first case, if you moved to the right once the result would be zero, because it would add a zero where 1 was.

8

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

A circular change is the operation of rearranging the inputs into a tuple, or moving from the final input to the first position, while changing all other inputs to the next position, or performing the reverse operation. A circular change is a special type of cycle , which in turn is a special type of permutation.

The image below illustrates this.

inserir a descrição da imagem aqui


Example

If the bit sequence 0001 0111 were subject to a circular change of a bit position:

To the left the result would be:

inserir a descrição da imagem aqui

To the right the result would be:

inserir a descrição da imagem aqui

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

  • To the left is: 1011 1000.
  • To the right is: 1110 0010.

2

Running 8 bits to the left
00000111
00001110
00011100
00111000
01110000
11100000
11000001
10000011

Running 8 bits to the right
00000111
10000011
11000001
11100000
01110000
00111000
00011100
00001110
00000111

Browser other questions tagged

You are not signed in. Login or sign up in order to post.