无符号整数如何工作
How do unsigned integers work
正如标题所暗示的那样,我很好奇unsigned int
(或像NSUInteger
,u_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的补充,因为它可能会回答你关于这个问题的所有问题。
- QSqlquery prepare()和bindvalue()不工作
- 导入库可以跨dll版本工作吗
- 以螺旋方式打印矩阵的程序.(工作不好)
- 对象指针在c++中是如何工作的
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++为线程工作动态地分割例程
- 为什么我的 std::ref 无法按预期工作?
- 布尔比较运算符是如何在C++中工作的
- SampleConsensusPrerejective(ext.RANSAC)是如何真正工作的
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- <<操作员在下面的行中工作
- 有人能解释一下为什么下界是这样工作的吗C++的
- ExtractIconEx:可以工作,但偶尔会崩溃
- C++中的memset函数工作不正常
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 当 int 方法工作正常时,void 方法有何不同,或者为什么我不能调用 void 方法?
- sdl软件渲染器不工作,工作在硬件加速的一个