简体   繁体   English

int值是否通常转换为unsigned?

[英]When is int value ordinarily converted to unsigned?

Here is from C++ Prime 5th : 这是来自C ++ Prime 5th

if we use both unsigned and int values in an arithmetic expression, the int value ordinarily is converted to unsigned. 如果我们在算术表达式中使用unsigned和int值,则int值通常会转换为unsigned。

And I tried the following code: 我尝试了以下代码:

int i = -40;
unsigned u = 42;
unsigned i2 = i;
std::cout << i2 << std::endl; // 4294967256
std::cout << i + u << std::endl; // 2 

For i + u , if i is converted to unsigned , it shall be 4294967256 , and then i + u cannot equal to 2 . 对于i + u ,如果i转换为unsigned ,则应为4294967256 ,然后i + u不能等于2

Is int value always converted to unsigned if we use both unsigned and int values in an arithmetic expression? int值始终转换为unsigned ,如果我们同时使用unsignedint的算术表达式的值?

Yes. 是。

What you're experiencing is integer overflow . 您遇到的是整数溢出 The sign of a negative number is given by the leading sign bit , which is either 0 (positive) or 1 (negative). 负数的符号由前导符号位给出 ,其为0(正)或1(负)。 However, for unsigned integers, this leading bit just gives you one more bit of integer precision, rather than an indication of sign. 但是,对于无符号整数,这个前导位只会给你一个整数精度位,而不是符号的指示。 "Negative" signed numbers end up counting backwards from the maximum unsigned integer size. “否定”有符号数字最终从最大无符号整数大小向后计数。

How does this relate to your particular code? 这与您的特定代码有何关系? Well, -40 does get turned into 4294967256. However, 4294967256+42 can't fit in an unsigned integer, as if you remember -40 just turned into the max unsigned integer minus 39. So by adding 42, you exceed the capacity of your data-type. 好吧,-40确实变成了4294967256.但是,4294967256 + 42不能放入无符号整数,好像你记得-40刚刚变成最大无符号整数减39.这样加上42,就超过了容量你的数据类型。 The would-be 33rd bit just gets chopped off, and you start over from 0. Hence, you still get 2 as an answer. 想要的第33位被切断,你从0开始。因此,你仍然得到2作为答案。

Signed:             -42,        -41, ...,         -1, 0, 1, 2
Unsigned:    4294967256, 4294967257, ..., 4294967295, 0, 1, 2, ...
                                                   ^--^ Overflow!

You'd probably be interested in reading about Two's Complement 你可能有兴趣阅读关于Two's Complement的内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM