Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum value of unsigned char

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

like image 635
Variance Avatar asked Jul 30 '10 16:07

Variance


1 Answers

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;
}
like image 52
Billy ONeal Avatar answered Oct 08 '22 14:10

Billy ONeal