Search code examples
ccharintunsigned-integerunsigned-char

Converting unsigned char to signed int


Consider the following program

void main(){
  char t = 179;
  printf("%d ",t);
}

Output is -77. But binary representation of 179 is

10110011

So, shouldn't output be -51, considering 1st bit is singed bit. Binary representation of -77 is

11001101

It seems bit order is reversed. What's going on? Please somebody advice.


Solution

  • You claimed that the binary representation of -77 is 11001101, but the reversal is yours. The binary representation of -77 is 10110011.

    Binary 10110011 unsigned is decimal 179.

    Binary 10110011 signed is decimal -77.

    You assigned the out-of-range value 179 to a signed char. It might theoretically be Undefined Behaviour, but apart from throwing an error, it would be a very poor compiler that placed anything but that 8-bit value in the signed char.

    But when printed, it's interpreted as a negative number because b7 is set.