vendredi 31 juillet 2015

Signed and unsigned characters behavior while printing in C

I have compiled the following C Program in Code::Blocks 10.05 on Windows 7.

int main()
{
    unsigned char a=-5;
    signed char b=-5;
    char c=-5;
    printf("%d  %d  %d \n",a,b,c);
    printf("%u  %u  %u \n",a,b,c);
}

I expected the following output

251 -5 -5
251 251 251

I have reasoned like this,

-5 is represented as 1111 1011 in 2's Complement Notation. Hence 251 will be printed.

But I got the following output.

251 -5 -5 
251 4294967291 4294967291

I know 4294967291 is the 32 bit 2's Complement representation of -5.

But why the unsigned char a is printed as 251 instead of 4294967291?

Aucun commentaire:

Enregistrer un commentaire