有符号整数和无符号整数之间的区别是:

Unsigned值可以是一个较大的正数,而不能是负数。 Unsigned版本使用前导位作为值的一部分,而signed版本使用最左边的位来识别数字是正还是负。 有符号整数可以同时包含正数和负数。

还有其他区别吗?


当前回答

根据我们在课堂上学到的,有符号整数既可以表示正数也可以表示负数,而无符号整数只能表示非负数。

例如,看一个8位的数字:

无符号值为0到255

带符号的取值范围为-128 ~ 127

其他回答

另一个区别是在不同大小的整数之间进行转换时。

例如,如果你从字节流中提取一个整数(简单来说就是16位),使用无符号值,你可以这样做:

i = ((int) b[j]) << 8 | b[j+1]

(可能应该强制转换第二个字节,但我猜编译器会做正确的事情)

对于有符号的值,你必须担心符号扩展,并做:

i = (((int) b[i]) & 0xFF) << 8 | ((int) b[i+1]) & 0xFF

一般来说,这是正确的。在不知道你为什么要寻找差异的情况下,我想不出有符号和无符号之间的任何其他区别。

在C语言中,有符号值和无符号值之间唯一保证的区别是有符号值可以为负、0或正,而无符号值只能为0或正。问题是C语言没有定义类型的格式(所以你不知道你的整数是2的补数)。严格来说,你提到的前两点是不正确的。

关于这个问题,我找到的最佳答案要感谢IBM引用的XDR标准:

Integer An XDR signed integer is a 32-bit piece of data that encodes an integer in the range [-2147483648,2147483647]. The integer is represented in two's complement notation. The most and least significant bytes are 0 and 3, respectively. The data description of integers is integer. Unsigned integer An XDR unsigned integer is a 32-bit piece of data that encodes a nonnegative integer in the range [0,4294967295]. It is represented by an unsigned binary number whose most and least significant bytes are 0 and 3, respectively. The data description of unsigned integers is unsigned.

参见维基百科上的XDR标准

除了第二点,其他都是正确的。有符号整型有许多不同的表示法,有些实现使用第一种,有些使用最后一种,还有一些使用完全不同的表示法。这取决于你所使用的平台。