无符号整数如何工作

How do unsigned integers work

本文关键字:工作 何工作 无符号整数      更新时间:2023-10-16

正如标题所暗示的那样,我很好奇unsigned int(或像NSUIntegeru_int_blah这样的东西,但我认为这些都是同一件事typedef)是如何工作的。例如,当它们的值降至零以下时,是否会提高 exion?会发生错误吗?这方面的一个具体示例是间接将值设置为负数。

for (unsigned int x = 5; x > -10; x--) {
    // will x ever reach below zero, or will the loop terminate
}


此外,间接设置它的另一种方法是让用户输入它。

printf("Enter a number");
unsigned int x;
scanf("%ud", &x); // user enters something like -29


所以真的,我有三个问题。什么阻止和无符号 int 被分配给负数 ( unsigned int x = - 3 )。如何实现此行为(通过编译器或其他方式)。将无符号 int (直接或间接)赋值为负值时会发生什么情况。数据是否已损坏?它会溢出吗?
谢谢

当一个无符号与有符号的比较时,它们都会被投射到无符号中。该过程与数据存储在内存中的方式有关。在二进制中,一个减号(如-3)将存储如下:

-3 : 1111 1111 1111 1101
3  : 0000 0000 0000 0011

你可以说 -3 可以像:

// result  : 0000 0000 0000 0011
result = for_every_bit_of_3( not **ThisBit** );  
// result  : 1111 1111 1111 1100 
result = result + 1;
// result  : 1111 1111 1111 1101 

所以循环:

for (unsigned int x = 5; x > -10; x--) {
    // will x ever reach below zero, or will the loop terminate
}

会像

// 4,294,967,286 is what -10 cast to unsigned
for (unsigned int x = 5; x > 4294967286; x--) {
    // will x ever reach below zero, or will the loop terminate
}

当您分配负数时

unsigned int = -1;

你得到的数字将是4294967295,或 4^8 -1

因为整数的大小是 4 字节,或者 4^8 = 4294967296

如果整数为负数,则整数将环绕此数字

作为对第一个代码示例的回答,循环将编译(但如果您使用 gcc 编译并具有 -Wno-sign-compare 标志,则会发出警告)。然而,运行它通常会导致循环根本无法运行,因为大多数系统使用 Two 的补码 (http://en.wikipedia.org/wiki/Two%27s_complement),这意味着 -10 与大于 5 的 4294967286 相同(假设 4 字节整数,但通常为 2*INT_MAX - 10)。一般来说,我建议阅读Two的补充,因为它可能会回答你关于这个问题的所有问题。