Maximum value of unsigned char

Variance picture Variance · Jul 30, 2010 · Viewed 24.1k times · Source
#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.

Answer

Billy ONeal picture Billy ONeal · Jul 30, 2010

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 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;
}