i have written a small program below.
#include <stdio.h>
main(){
char a=-1;
unsigned char b=-1;
printf("%d %d\n",a,b);
printf("%x %x\n",a,b);
if(a==b) printf("equal\n");
else printf("not equal\n");
}
The output of the prog is :
-1 255
ffffffff ff
not equal
since char is only one byte and -1 is represented in 2’s complement form, i thought that 0xff will be stored in both a & b and hence both should be equal. Can anyone let me know why they are different and why hex rep’n of a is 0xffffffff & not 0xff. i got a related link http://embeddedgurus.com/stack-overflow/2009/08/a-tutorial-on-signed-and-unsigned-integers/ but i couldn’t get the answer. any help will be greatly appreciated. thanks.
They are the same. Or rather, their underlying representation is the same (under the assumption that your compiler use two-complement form).
On the other hand, the values they represent are -1 and 255.
When you print them, they are extended to the data type
int.unsigned charis zero-extended whereas a signed char is sign extended, which accounts for the differences you see.The same extension occurs when you compare the two values.
a == bdon’t compare the underlying representations, instead, it extends both values tointso it compares 255 with -1, which isn’t equal.Note that a plain
charmay be either signed or unsigned. In your environment, it is obviously signed.