#include <stdio.h>
int main()
{
unsigned char i=0x80;
printf("%d",i<<1);
return 0;
}
Why does this program print 256?
As I understand this, since 0x80= 0b10000000, and unsigned char has 8 bits, the '1' should overflow after left shift and the output should be 0, not 256.
Best Answer
This is a result of C's integer promotion rules. Essentially, most any variable going into an expression is "promoted" so that operations like this do not lose precision. Then, it's passed as an
int
intoprintf
, according to C's variable arguments rules.If you'd want what you're looking for, you'd have to cast back to
unsigned char
:Note: using
%c
as specified in Stephen's comment won't work because%c
expects an integer too.EDIT: Alternately, you could do this:
or