Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rotation of unsigned char by n bits

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

like image 592
CHID Avatar asked Jan 22 '14 17:01

CHID


People also ask

Which code is used for rotating the data bit by bit from left?

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.

How do you rotate a bit in Java?

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).


1 Answers

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).

like image 106
Sergey Kalinichenko Avatar answered Sep 19 '22 01:09

Sergey Kalinichenko