Problem: Exercise 2-8 in the C programming language: "Write a function rightrot (x, n) that returns the value of an integer x rotated to the right by n positions."
I did it the way I know. That is the question I have. Take a specific number for this exercise, say 29, and turn it one position to the right.
11101, and it will become 11110 or 30. Let's say, for the sake of argument, that the system we are working on has an unsigned integer size of 32 bits. Let it be said further that we have the number 29 stored in an unsigned integer variable. In memory, the number will have 27 zeros in front. Therefore, when we rotate 29 right, using one of several algorithms, my wire is placed below, we get the number 2147483662. This is obviously not the desired result.
unsigned int rightrot(unsigned x, int n) { return (x >> n) | (x << (sizeof(x) * CHAR_BIT) - n); }
This is technically correct, but I thought the 27 zeros that are in front of 11101 were minor. I also tried several other solutions:
int wordsize(void) { // compute the wordsize on a given machine... unsigned x = ~0; int b; for(b = 0; x; b++) x &= x-1; return x; } unsigned int rightrot(unsigned x, int n) { unsigned rbit; while(n --) { rbit = x >> 1; x |= (rbit << wordsize() - 1); } return x;
This last and final decision is one in which I thought I had it, I will explain where he failed as soon as I get to the end. I am sure you will see my mistake ...
int bitcount(unsigned x) { int b; for(b = 0; x; b++) x &= x-1; return b; } unsigned int rightrot(unsigned x, int n) { unsigned rbit; int shift = bitcount(x); while(n--) { rbit = x & 1; x >>= 1; x |= (rbit << shift); } }
This solution gives the expected answer 30, which I was looking for, but if you use a number for x, for example, say 31 (11111), then there are problems, in particular, the result is 47, using one for n. I had not thought about this before, but if a number like 8 (1000) is used, then chaos. There is only one bit in 8 bits, so the shift will certainly be wrong. My theory at this stage is that the first two solutions are correct (mostly), and I just missed something ...