I’m a little bit confused as to what an unsigned char is. A signed char is the representation of the char in bit form right? A sample problem has us rotating to the right by n bit positions, the bits of an unsigned char with this solution:
unsigned char rotate(unsigned char x, int n) {
unsigned char temp = x << 8 - n;
x = x >> n;
return (x | temp);
}
If anyone could explain with char examples and their respective bits, it would be greatly appreciated. Thanks so much.
Declaring a variable as
unsigned chartells the compiler to treat the underlying bit pattern as a number from 0 (00000000) to 255 (11111111). Declaring it achartells the compiler to apply two’s complement to the underlying bit pattern and treat it as a number from -128 (10000000) to 127 (01111111).Consider a 3-bit number. If it is unsigned, you have:
If it is signed you have:
What is neat with respect to arithmetic (as that link mentions) is that you don’t have to treat signed binary numbers differently than unsigned ones. You just do the actual binary math without regard to signed or unsigned. But you do have to apply the signed/unsigned interpretation to the inputs and to the output.
In the signed realm you might have:
But in the unsigned realm this is:
So it’s all a matter of interpretation since the actual bit patters being added and the bit pattern of the sum are the same in both cases.