Why stores 255 in a char variable give its value -1 in C?

后端 未结 5 1173
夕颜
夕颜 2021-01-03 06:29

I am reading a C book, and there is a text the author mentioned:

\"if ch (a char variable) is a signed type, then storing 255 in the ch variable gives it the

5条回答
  •  醉酒成梦
    2021-01-03 06:48

    You have classical explanation in others messages. I give you a rule:

    In a signed type with size n, presence of MSB set as 1, must interpreted as -2^(n-1).

    For this concrete question, assuming size of char is 8 bits length (1 bytes), 255 to binary is equal to:

    1*2^(7) +  
    1*2^(6) + 
    1*2^(5) + 
    1*2^(4) + 
    1*2^(3) + 
    1*2^(2) + 
    1*2^(1) + 
    1*2^(0) = 255
    
    255 equivalent to 1 1 1 1 1 1 1 1.
    

    For unsigned char, you get 255, but if you are dealing with char (same as signed char), MSB represents a negative magnitude:

    -1*2^(7) +  
    1*2^(6) + 
    1*2^(5) + 
    1*2^(4) + 
    1*2^(3) + 
    1*2^(2) + 
    1*2^(1) + 
    1*2^(0) = -1
    

提交回复
热议问题