是转换int->标准定义的unsigned long long [英] Is conversion int -> unsigned long long defined by the standard
问题描述
我找不到标准中将 int
值如何转换为 unsigned long long
的确切说明.指定了各种类似的转换,例如int-> unsigned,unsigned-> int(如果为负,则为UB),unsigned long long-> int等
I can't find the exact specification of how int
value is converted to unsigned long long
in the standard. Various similar conversions, such as int -> unsigned, unsigned -> int (UB if negative), unsigned long long -> int, etc. are specified
例如,GCC将 -1
转换为 0xffffffffffffffff
,而不是 0x00000000ffffffff
.我可以依靠这种行为吗?
For example GCC, -1
is converted to 0xffffffffffffffff
, not to 0x00000000ffffffff
. Can I rely on this behavior?
推荐答案
是的,它定义明确,基本上是在 -1
max unsigned long long + 1 >始终为 max unsigned long long
.草稿C ++标准 4.7
积分转换部分,其中:
Yes, this is well defined, it is basically adding max unsigned long long + 1
to -1
which will always be max unsigned long long
. This is covered in the draft C++ standard section 4.7
Integral conversions which says:
如果目标类型是无符号的,则结果值是与源整数一致的最小无符号整数(模2 n ,其中n是用于表示无符号类型的位数).[注意:在二进制补码表示中,此转换是概念性的,并且位模式没有任何变化(如果没有截断的话).—尾注]
If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type). [ Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). —end note ]
它的功能与C99相同,但草稿从 6.3.1.3
有符号和无符号整数:
it does the same thing as C99 but the draft C99 standard is easier to understand, from section 6.3.1.3
Signed and unsigned integers:
否则,如果新类型是无符号的,则通过重复加或比新类型可以表示的最大值多减去一个直到该值在新类型的范围内. 49)
其中脚注 49
说:
规则描述的是数学值的算术运算,而不是给定类型的表达式的值.
The rules describe arithmetic on the mathematical value, not the value of a given type of expression.
这篇关于是转换int->标准定义的unsigned long long的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!