再举一个例子来展示无符号数据类型会环绕
而不是溢出:
unsigned int i = std::numeric_limits<unsigned int>::max()
将-ve
数赋值给unsigned
不建议使用,但为了说明目的,下面我将使用它。
unsigned int j = -1; // 4294967295 wraps around(uses modulo operation)
unsigned int j = -2; // 4294967294
通过对于 max+1
取模(其中 max = 2^n),来可视化无符号的 (0 to max)
范围:
Range : 0, 1, 2,......., max-2, max-1, max
.................................................................................
Last-to-First : -(max+1), -max, -(max-1),......., -3, -2, -1
First-to-Last : max+1, max+2, max+3,......., max+max-1, max+max, max+max+1
模数加法规则: (A + B) % C = (A % C + B % C) % C
[max + max + 1]
= [(max
= [(max
= [max]
= max