two's complement

Q: What is two's complement(补码)?

The two's complement of a is 2^N-a.

Q: What is one's complement?

The one's complement of a is (2^N-1)-a. Generally (2^N-1) is all 1, e.g. 2^4-1 is 1111. So this is called one's complement.

Q: In address 0x100, data 1010 1100 (let's name the value as a) is stored. From the value, can we know it's signed or unsigned value?

The answer is definitely NO. a can be considered as unsigned char (value will be -84), it can be also considered as signed char (value will be 172). There is also no another flag indicating us how to consider it, so we don't know the memory a should be considered as signed or unsigned.

We don't know, and the computer also don't know.

Take one example 0xFC + 0x05:

                signed   unsigned
   1111 1100     -4       252     :  0xFC
+  0000 0101      5        5      :  0x05 
--------------
  10000 0001      1       257
                 No       Yes     :  overflow?

In upper example,

  • the result is not overflow if we consider them as signed number. So the result is right.
  • the reulst is overflow if we consider them as unsigned number, so the result is wrong, generally one exception will be reporte.

Which result I should used?
The answer is depends on you, not depends on the CPU. The good thing is that the CPU will tell to you the overflow flag based on signed and unsigned together.

The overflow flag based on signed type is OF, the flag based on unsigned type is CF.

猜你喜欢

转载自www.cnblogs.com/byronxie/p/10117265.html