What is the difference between signed and unsigned variables?

后端 未结 8 1027
一个人的身影
一个人的身影 2020-12-07 13:04

I have seen these mentioned in the context of C and C++, but what is the difference between signed and unsigned variables?

8条回答
  •  执念已碎
    2020-12-07 13:57

    Unsigned variables are variables which are internally represented without a mathematical sign (plus or minus) can store 'zero' or positive values only. Let us say the unsigned variable is n bits in size, then it can represent 2^n (2 power n) values - 0 through (2^n -1). A signed variable on the other hand, 'loses' one bit for representing the sign, so it can store values from -(2^(n-1) -1) through (2^(n-1)) including zero. Thus, a signed variable can store positive values, negative values and zero.

    P.S.:
    Internally, the mathematical sign may be represented in one's complement form, two's complement form or with a sign bit (eg: 0 -> +, 1-> -)
    All these methods effectively divide the range of representable values in n bits (2^n) into three parts, positive, negative and zero.

    This is just my two cents worth.

    I hope this helps.

提交回复
热议问题