Question

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!

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top