Simple Character Interpretation In C

后端 未结 9 909
暖寄归人
暖寄归人 2021-01-06 12:54

Here is my code

 #include

 void main()
 {
     char ch = 129;
     printf(\"%d\", ch);
 }

I get the output as -127. What d

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-06 13:33

    This comes from the fact that a char is coded on one byte, so 8 bits of data.

    In fact char has a value coded on 7 bits and have one bit for the sign, unsigned char have 8 bits of data for its value.

    This means:

    Taking abcdefgh as 8 bits respectively (a being the leftmost bit, and h the rightmost), the value is encoded with a for the sign and bcdefgh in binary format for the real value:

    42(decimal) = 101010(binary) stored as : abcdefgh 00101010

    When using this value from the memory : a is 0 : the number is positive, bcdefgh = 0101010 : the value is 42

    What happens when you put 129 :

    129(decimal) = 10000001(binary) stored as : abcdefgh 10000001

    When using this value from the memory : a is 0 : the number is negative, we should substract one and invert all bits in the value, so (bcdefgh - 1) inverted = 1111111 : the value is 127 The number is -127

提交回复
热议问题