1. ## [HW] Bit rotation

Hi,

Im trying to create a bit rotate function for a "hexadecimal calculator". I found a code in wikipedia that seems to work:

Code:
`unsigned int x;  unsigned int y;  /* ... */  y = (x << shift) | (x >> (sizeof(x)*CHAR_BIT - shift));`
However, i want to rewrite it on my own but i want to know the formula behind it, like what is "CHAR_BIT" for? Is it the number of bits the answer will be shown?

2. sizeof(x) tells you the number of bytes in x
CHAR_BIT tells you the number of bits in a byte (it's usually 8)
The whole thing tells you the number of bits in x

ok i played with it a bit using hexadecimal 49 and 10. I got the same answer (49000) even though i just used:

(x << shift) | (x >> (x - shift)).

4. Except your formula is not correct.

5. ok, i was able to get a solution for the bit wise rotation without using the sizeof() function for rotate right:

Code:
```temp = n1 & 0x1;
n1 >>= 1;
n1 = n1 | (temp << 31);```
however, im still curious about sizeof(). i tried hexadecimal "num1 = a" shift by "num2 = 5" but used just the "sizeof(num1)*8 - num2" part of the forumla.. i got 1b. im using unsigned int and got "4" from sizeof(num1) regardless of the value in num1. i just want to know the logic behind it since it was not very well explained in the wiki page it came from.

6. Originally Posted by Warzaw
im using unsigned int and got "4" from sizeof(num1) regardless of the value in num1.
That's because sizeof doesn't care about the value. It only looks at the type and gives you the size in bytes for that type in your implementation. So for your system, an unsigned int uses 4 bytes thus the possible values are 0 to (2^32 -- 1) [= 4294967295]. But the C standard only says that the maximum value for an unsigned int must be at least (2^16 - 1) [= 65535] so there can be systems where an unsigned int is stored in only 2 bytes and systems where an unsigned int is stored in more than 4 bytes.

Hence, you use sizeof if you want to write portable programs.