为什么 00000000 - 00000001 = 11111111 在 C unsigned char 数据类型中?

why is 00000000 - 00000001 = 11111111 in C unsigned char data type?

我观察到,当一个 unsigned char 变量存储值 0 (000000002) 并且它被递减 1 (000000012),变量值变为255(111111112),这是unsigned char变量所能容纳的最大值

我的问题是:为什么 000000002 - 000000012 变成 111111112? (想看看背后的算法)

我观察到的C代码是这个:

#include <stdio.h>

main(){

  unsigned char c = 0;

  unsigned char d = c - 1;

  printf("%d\n%d", c, d);

}

运行时,显示以下输出:

0
255

参见here

Unsigned integer arithmetic is always performed modulo 2n where n is the number of bits in that particular integer. E.g. for unsigned int, adding one to UINT_MAX gives ​0​, and subtracting one from ​0​ gives UINT_MAX.

所以在你的例子中,由于 unsigned char 通常是 8 位,你得到 28-1 = 255.