What is the difference between signed and unsigned variables?

后端 未结 8 995
一个人的身影
一个人的身影 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 14:03

    Signed variables, such as signed integers will allow you to represent numbers both in the positive and negative ranges.

    Unsigned variables, such as unsigned integers, will only allow you to represent numbers in the positive.

    Unsigned and signed variables of the same type (such as int and byte) both have the same range (range of 65,536 and 256 numbers, respectively), but unsigned can represent a larger magnitude number than the corresponding signed variable.

    For example, an unsigned byte can represent values from 0 to 255, while signed byte can represent -128 to 127.

    Wikipedia page on Signed number representations explains the difference in the representation at the bit level, and the Integer (computer science) page provides a table of ranges for each signed/unsigned integer type.

    0 讨论(0)
  • 2020-12-07 14:03

    Unsigned variables can only be positive numbers, because they lack the ability to indicate that they are negative.

    This ability is called the 'sign' or 'signing bit'.

    A side effect is that without a signing bit, they have one more bit that can be used to represent the number, doubling the maximum number it can represent.

    0 讨论(0)
提交回复
热议问题