# definition
数值定义. 对于 N-bit two's complement number system, 最高位 N-th bit 为符号位, 0 为正,
1 为负. 对于任意一个非负整数, 它的相反数为 its complement with respect to $2^N$.

# properties

-   一个数字的 two's complement 可以通过:
    1.  take its ones' complement and add one.
        因为: the sum of a number and its ones' complement is -0, i.e. ‘1’ bits, or $2^N-1$;
        and by definition, the sum of a number and its two's complement is $2^N$.
    2.  通过定义中的 unsigned binary arithmetic 计算得出.
-   The value of A N-bit binary number in two's complement numercal system can be computed by
    $$w = -a_{N-1} 2^{N-1} + \sum_{i=0}^{N-2} a_i 2^i$$. 推导: 对于互为相反数的 $A$ 和 $B$,
    已知:
    $$
    \begin{align}
        A + B &= 0 \\
        A &= \sim B + 1
    \end{align}
    $$
    第二式为 two's complement 和 ones' complement 的关系.
    根据第二式得到
    $$
    A=1+\sum_{i=0}^{N-1}(1-b_i)2^i
    $$
    对于 N-bit number system, $A+B=0$ 意味着
    $$(A+B) \operatorname{mod} 2^N = 0$$
    满足上式的 $B$ 有两种设计方式:
    $$
    \begin{align}
        B &= b_{N-1}2^{N-1} + \sum_{i=0}^{N-2}b_i 2^i \\
        B &= -b_{N-1}2^{N-1} + \sum_{i=0}^{N-2}b_i 2^i
    \end{align}
    $$
    分别对应于 unsigned number 和 signed number 的数值公式.
-   most negative number, `INT_MIN`. 它没有可以在系统内表达的相反数. 因为正负数范围的不对称性.
    根据 two's complement 的定义计算 `INT_MIN` 得到的是自身, 这显然是不对的.
-   加减法. 普通的二进制加减法运算即可, 没有特殊处理. 
-   加减法的溢出检测. an XOR operation on leftmost two carry/borrow bits can quickly determine
    if an overflow condition exists.




```python

```

57e58ee67b325cd5a78841b53ba007ba4ce08912
ipynb
Jupyter Notebook
math/arithmetic/binary-arithmetic/two-s-complement.ipynb
Naitreey/notes-and-knowledge
48603b2ad11c16d9430eb0293d845364ed40321c
BSD-3-Clause
2018-05-16T06:06:45.000Z
2021-05-12T08:46:18.000Z
math/arithmetic/binary-arithmetic/two-s-complement.ipynb
Naitreey/notes-and-knowledge
48603b2ad11c16d9430eb0293d845364ed40321c
BSD-3-Clause
2018-04-06T01:46:22.000Z
2019-02-13T03:11:33.000Z
math/arithmetic/binary-arithmetic/two-s-complement.ipynb
Naitreey/notes-and-knowledge
48603b2ad11c16d9430eb0293d845364ed40321c
BSD-3-Clause
2019-04-11T11:02:32.000Z
2020-06-27T11:59:09.000Z
Qwen/Qwen-72B
1. YES
2. YES