Search code examples
ccastingunsigned

Can Some one explain why I get these output?


I am new to c.

My Question.

Why do some numbers end up negative when the value was positive?


Solution

  • Here is an explanation for the output you are seeing. 1000 in binary is 1111101000 (10 bits) and is stored in an int (signed 32 bits)

    When you cast that to an unsigned char (that has 8 bits), the top bits get "cut off".

    So you get: 11101000 which is 232 in decimal.

    As a (signed) char, the bits get interpreted as a negative number because the first (sign) bit is set, which in this case is -24.

    When you remove the sign bit, 1101000 = 104

    The "value" of the MSB is 128, so your computer does 104 - 128 = -24.

    (See https://en.wikipedia.org/wiki/Two%27s_complement)

    A long has the same or more bits as an int so the value does not change.