I need help solving this problem in my mind, so if anyone had a similar problem it would help me.
Here’s my code:
char c=0xAB;
printf("01:%x\n", c<<2);
printf("02:%x\n", c<<=2);
printf("03:%x\n", c<<=2);
Why the program prints:
01:fffffeac
02:ffffffac
03:ffffffb0
What I expected to print, that is, what I got on paper is:
01:fffffeac
02:fffffeac
03:fffffab0
I obviously realized I didn’t know what the operator <<=
was doing, I thought c = c << 2
.
If anyone can clarify this, I would be grateful.
>Solution :
You’re correct in thinking that
c <<= 2
is equivalent to
c = c << 2
But you have to remember that c
is a single byte (on almost all systems), it can only contain eight bits, while a value like 0xeac
requires 12 bits.
When the value 0xeac
is assigned back to c
then the value will be truncated and the top bits will simply be ignored, leaving you with 0xac
(which when promoted to an int
becomes 0xffffffac
).