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!
4 * (8 - 2)
should be4*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 Oehm0x1011 >> 30
is zero. Pick a number with high bits or rotate0x1011
by 30 bits. – M Oehm