Reputation: 2311
unsigned char x = 93;
unsigned char a = x << 4;
printf("a = %d\n", a);
I do understand how bit operators work but I don't understand the binary representation of x.
How is a = 208?
Upvotes: 2
Views: 2150
Reputation: 3184
Mathematically it corresponds to the following:
x<<4 is x*16, so x*16 = 93*16 = 1488
but a is an unsigned char (ie 0<=a<256), so a = 1488 modulo 256 = 208
Upvotes: 1
Reputation: 29618
93 = 0x5d
0x5d << 4 = 0x5d0
0x5d0 & 0xff = 0xd0
0xd0 = 208
i.e. what has happened here is that the top bits have been cut off.
Upvotes: 1
Reputation: 3834
That's because an unsigned char can only be as big as 255(1111 1111 in binary). If a number is left-shifted, all bits that go out of its bounds are lost. 0b11111111 << 1 = 0b11111110
So, if you get 93 in binary(0101 1101) and left shift it 4 times you'll get 1101 0000 -the 4 leftmost bits are forever lost.
Upvotes: 0
Reputation: 490623
x = 93 = 0x5D = 0101 1101
<< 4 = 1101 0000
1101 0000 in decimal is 208.
Upvotes: 3
Reputation: 41252
93 = 01011101
Shift that left 4 bits and it leaves the following (only 8 bits in your result):
11010000 = 208
Upvotes: 4