What does signed and unsigned values mean?

后端 未结 9 857
旧巷少年郎
旧巷少年郎 2020-12-14 02:28

What does signed mean in C? I have this table to show:

\"enter

Th

相关标签:
9条回答
  • 2020-12-14 03:27

    A signed integer can represent negative numbers; unsigned cannot.

    Signed integers have undefined behavior if they overflow, while unsigned integers wrap around using modulo.

    Note that that table is incorrect. First off, it's missing the - signs (such as -128 to +127). Second, the standard does not guarantee that those types must fall within those ranges.

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

    By default, numerical values in C are signed, which means they can be both negative and positive. Unsigned values on the other hand, don't allow negative numbers.

    Because it's all just about memory, in the end all the numerical values are stored in binary. A 32 bit unsigned integer can contain values from all binary 0s to all binary 1s. When it comes to 32 bit signed integer, it means one of its bits (most significant) is a flag, which marks the value to be positive or negative. So, it's the interpretation issue, which tells that value is signed.

    Positive signed values are stored the same way as unsigned values, but negative numbers are stored using two's complement method.

    If you want to write negative value in binary, first write positive number, next invert all the bits and last add 1. When a negative value in two's complement is added to a positive number of the same magnitude, the result will be 0.

    In the example below lets deal with 8-bit numbers, because it'll be simple to inspect:

    positive 95: 01011111
    negative 95: 10100000 + 1 = 10100001 [positive 161]
              0: 01011111 + 10100001 = 100000000
                                        ^
                                        |_______ as we're dealing with 8bit numbers,
                                                 the 8 bits which means results in 0
    
    0 讨论(0)
  • 2020-12-14 03:31

    Nobody mentioned this, but range of int in table is wrong: it is

    -2^(31) to 2^(31)-1
    

    i.e.,

    -2,147,483,648 to 2,147,483,647
    
    0 讨论(0)
提交回复
热议问题