简体   繁体   English

从unsigned long long转换为unsigned int

[英]converting from unsigned long long to unsigned int

I was searching around a little trying to find an answer to this, but I couldn't find a clear cut answer. 我正在寻找一个小小的试图找到答案,但我找不到明确的答案。
I saw this answer where he wrote as a side note: 我看到这个答案,他写的是旁注:

The rules are different for unsigned types; 对于无符号类型,规则是不同的; the result of converting a signed or unsigned integer to an unsigned type is well defined. 将有符号或无符号整数转换为无符号类型的结果已得到很好的定义。

So what is the well defined behavior? 那么明确定义的行为是什么?
When converting from unsigned long long to unsigned int is there a defined behavior? unsigned long long转换为unsigned int是否存在已定义的行为? Is it just cutting off the 32 MSB's? 它只是切断了32 MSB的? (leaving me with the 32 LSB's). (留下我的32 LSB)。
Lets assume that sizeof(unsigned int) is 4 and sizeof(unsigned long long) is 8 in my system. 让我们假设sizeof(unsigned int)4sizeof(unsigned long long)在我的系统中是8
Is there a different behavior when assigning without casting and when assigning with casting? 在没有强制转换的情况下进行分配以及使用强制转换进行分配时是否存在不同

The standard says: 标准说:

6.3.1.3 Signed and unsigned integers 6.3.1.3有符号和无符号整数
1 When a value with integer type is converted to another integer type other than _Bool , if the value can be represented by the new type, it is unchanged. 1当具有整数类型的值转换为除_Bool之外的另一个整数类型时,如果该值可以由新类型表示,则它将保持不变。
2 Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type. 2否则,如果新类型是无符号的,则通过重复加或减一个可以在新类型中表示的最大值来转换该值,直到该值在新类型的范围内。 49) 49)
3 Otherwise, the new type is signed and the value cannot be represented in it; 3否则,新类型已签名且值无法在其中表示; either the result is implementation-defined or an implementation-defined signal is raised. 结果是实现定义的,或者引发实现定义的信号。

Point 2 describes a modulo operation, which has the same effect than cutting off the MSBs in this case. 第2点描述了模运算,与在这种情况下切断MSB具有相同的效果。 (It has the same effect when the maximum value of the new type plus one is a power of the number base.) (当新类型的最大值加1是数字基数的幂时,它具有相同的效果。)

There's no difference if you use casting. 如果你使用铸造没有区别。

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

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