c++ - 无符号整数如何工作

标签 c++ objective-c c types

如标题所示,我很好奇 unsigned int(或类似 NSUIntegeru_int_blah 的东西,但我认为这些是同一事物的所有 typedef)都有效。例如,当它们的值低于零时,是否会引发异常?会不会出错?一个具体示例是间接将值设置为负数。

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


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

最佳答案

unsigned 与 signed 比较时,都会被转为 unsigned。该过程与数据在内存中的存储方式有关。 在二进制中,负数(如 -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
}

关于c++ - 无符号整数如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22800589/

相关文章:

ios - 如何在不插入模型对象的情况下使用它?

C# 如何在 struct 中使用 struct array 进行 P/Invoke?

c 在 MAC OS X 上调用 DH_generate_key 例程时出现 openssl 校验和错误

c++ - 我不明白在C++11中如何实现乐观并发

c++ - static_cast 和 reinterpret_cast 的转换运算符 int() 失败

c - 将 Objective-C 类包装在 C 结构中以镜像类名

c - 代码中的 EXC_BAD_ACCESS 来自 Cracking the coding interview

android - 在 C++ 中打开创建的文件描述符的 Setvbuf?

c++ - 将多个类调用存储在一个变量中总是更快吗?

iphone - 获取对 UIApplication 委托(delegate)的引用