有符号整数和无符号整数之间的区别是:
Unsigned值可以是一个较大的正数,而不能是负数。 Unsigned版本使用前导位作为值的一部分,而signed版本使用最左边的位来识别数字是正还是负。 有符号整数可以同时包含正数和负数。
还有其他区别吗?
有符号整数和无符号整数之间的区别是:
Unsigned值可以是一个较大的正数,而不能是负数。 Unsigned版本使用前导位作为值的一部分,而signed版本使用最左边的位来识别数字是正还是负。 有符号整数可以同时包含正数和负数。
还有其他区别吗?
当前回答
(回答第二个问题)通过只使用符号位(而不是2的补码),你可以得到-0。不太漂亮。
其他回答
(回答第二个问题)通过只使用符号位(而不是2的补码),你可以得到-0。不太漂亮。
一般来说,这是正确的。在不知道你为什么要寻找差异的情况下,我想不出有符号和无符号之间的任何其他区别。
为了完整起见,这里只提几点:
this answer is discussing only integer representations. There may be other answers for floating point; the representation of a negative number can vary. The most common (by far - it's nearly universal today) in use today is two's complement. Other representations include one's complement (quite rare) and signed magnitude (vanishingly rare - probably only used on museum pieces) which is simply using the high bit as a sign indicator with the remain bits representing the absolute value of the number. When using two's complement, the variable can represent a larger range (by one) of negative numbers than positive numbers. This is because zero is included in the 'positive' numbers (since the sign bit is not set for zero), but not the negative numbers. This means that the absolute value of the smallest negative number cannot be represented. when using one's complement or signed magnitude you can have zero represented as either a positive or negative number (which is one of a couple of reasons these representations aren't typically used).
无符号整数比有符号整数更容易让您陷入特定的陷阱。陷阱来自于这样一个事实:虽然上面的1和3是正确的,但这两种类型的整数都可以被赋值到它可以“容纳”的范围之外,并且它将被无声地转换。
unsigned int ui = -1;
signed int si = -1;
if (ui < 0) {
printf("unsigned < 0\n");
}
if (si < 0) {
printf("signed < 0\n");
}
if (ui == si) {
printf("%d == %d\n", ui, si);
printf("%ud == %ud\n", ui, si);
}
运行此命令时,您将得到以下输出,尽管这两个值都赋值为-1,且声明方式不同。
signed < 0
-1 == -1
4294967295d == 4294967295d
除了第二点,其他都是正确的。有符号整型有许多不同的表示法,有些实现使用第一种,有些使用最后一种,还有一些使用完全不同的表示法。这取决于你所使用的平台。