views:

92

answers:

2
#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.

+9  A: 

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 pased as an int into printf, 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:

#include <stdio.h>
int main()
{
    unsigned char i=0x80;
    printf("%d",((unsigned char)(i<<1)));
    return 0;
}

Note: using %c as specified in Stephen's comment won't work because %c expects an integer too.

EDIT: Alternately, you could do this:

#include <stdio.h>
int main()
{
    unsigned char i=0x80;
    unsigned char res = i<<1;
    printf("%d",res);
    return 0;
}

or

#include <stdio.h>
int main()
{
    unsigned char i=0x80;
    printf("%d",(i<<1) & 0xFF);
    return 0;
}
Billy ONeal
+1 for completeness.
R..
Could you cast `(i<<1)` to `unsigned char`?
Nathon
@Nathon: Isn't that what I did?
Billy ONeal
Weird, I must have my blinders turned on.
Nathon
Thank you.­
Variance
+1  A: 

Don't forget the format specifically for printing unsigned.

printf("%u",(unsigned char)(i<<1));
Paul E.