Reputation: 1643
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
Upvotes: 6
Views: 1130
Reputation: 727047
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
).
Upvotes: 10