I am trying to rotate an unsigned char by 'n' bits. But I am not getting the desired result. This is my code
void left_rotate(unsigned char a, int no){
// no - number of times to rotate
printf("%d\n", ((a << no) | (a >> (8-no))));
}
I am calling this function from mail as follows
unsigned char a = 'A';
left_rotate(a, 2);
I expected the following output
//'A' = 65 = 01000001
// I am rotating in left direction by two times
// a << 2 = 00000100
// a >> 6 = 00000001
(00000100 | 00000001 = 00000101 = 5 in decimal)
But I got a different output
// The output in my screen = 100000101 = 261 in decimal
How did that 1 in MSB creep in? I am using an unsigned char as data type. So it shouldnt exceed 8 bits. Can someone please explain this?
Thanks
Chid
Bit Rotation: A rotation (or circular shift) is an operation similar to shift except that the bits that fall off at one end are put back to the other end. In left rotation, the bits that fall off at left end are put back at right end.
Java Integer rotateLeft() Method The rotateLeft() method of Java Integer class returns the value obtained by rotating the two's complement binary representation of the specified int value left by the specified number of bits. (Bits shifted out of the left hand, or high-order).
Since <<
promotes its arguments to unsigned int
, you need to mask off the upper bits of the shift result:
printf("%d\n", (((a << no) & 0xFF) | (a >> (8-no))));
Demo on ideone (prints 5
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With