1
votes

I need help understanding the C language. I just started out. I have this piece of code from wikipedia:

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

I do understand what rotation of bits means. I just don't understand this implementation. Why do I have to perform the OR operator here? And what does the right part actually do?

I shift value to the right for the number of bytes of value times (the number of bits in a char variable minus the shift I want). Why do I have to do this? If I think of an example. I want to shift unsigned 1011 (Base 2) 2 Bits to the left. I do what the code says:

0000 0000 0000 0000 0000 0000 0000 1011 << 2 = 0000 0000 0000 0000 0000 0000 0010 1100

1011 >> (4*(8-2))=24 = 0000 0000 0000 0000 0000 0000 0000 0000 0000;

perform |: = 0000 0000 0000 0000 0000 0000 0010 1100.

Ok that did not work. What am I doing wrong?

Thanks!

1
You've got the parentheses wrong: 4 * (8 - 2) should be 4*8 - 2. Also, why didn't that work? Your result is correct. The right shift just didn't contribute anything to your or operation.M Oehm
But I want to rotate left, not shift left. Shouldnt it be 1011 leftrot(2) = 1110 ? Or did I get the concept of rotation wrong and that only happens when the something like 1000 0000 0000 0000 1001 0000 1010 1100 is rotated?RunOrVeith
But you do that! Shifting means that the bits get pushed out at the left end. Rotating means that they reappear on the right. Your example hasn't got any high bits that could appear and 0x1011 >> 30 is zero. Pick a number with high bits or rotate 0x1011 by 30 bits.M Oehm
Ok, so if 1011 was stored in 4 bit, not 32, and I shift it 2 to the left I would get 1110?RunOrVeith
Yes, the 4-bit number 1011 would become 1110. Imagine your binary number as circular. Rotating just changes the starting point, not the bit pattern.M Oehm

1 Answers

1
votes

Here is a graphical definition of an 8-bit 'Shift Left', and 'Rotate Left':

enter image description here

"Why do I have to perform the OR operator here?" 
"And what does the right part actually do?"

For a 'rotate left' operation, the bits that "fall off" the left side are recycled, as they are 'OR'ed back into the right side.