从 '(signed) -1' 到 'unsigned long' 的转换是否标准化? [英] Is the conversion from '(signed) -1' to 'unsigned long' standardized?
问题描述
严格来说,转换前两个数字的位表示是否相同并不重要.即使使用 1 的补码或有符号幅度表示,(有符号)-1 到 unsigned long 的转换总是会导致 ULONG_MAX
.(转换后的位模式将相同当然).
我知道您可以用其他方式表示 -1
而不是 Two's Compliment,这是一个有效的补充,应该在我的回答中.但是,在这样的实现中,依赖于 ULONG_MAX
的转换是否安全?
是的,无论实际表示如何,都可以保证这一点:
[conv.integral](强调我的)><块引用>
整数类型的纯右值可以转换为另一个类型的纯右值整数类型.无作用域枚举类型的纯右值可以是转换为整数类型的纯右值.
如果目标类型是无符号的,则结果值是与源整数全等的最小无符号整数(模 2n其中 n
是用于表示无符号类型的位数).[ 注:在二进制补码表示中,这种转换是概念上并且位模式没有变化(如果没有截断).— 尾注 ]
In this answer, you can find this comment:
Strictly speaking the bit representations of the two numbers before conversion being the same doesn't matter. Even with 1's complement or signed magnitude representations, the conversion of (signed) -1 to unsigned long will always result in
ULONG_MAX
. (The bit pattern will be the same after conversion of course).
I understand that you can represent -1
in other ways than Two's Compliment, that's a valid addition that should be in my answer. But, in such implementations, is it safe to rely on the conversion to ULONG_MAX
?
Yes, this is guaranteed regardless of the actual representation:
[conv.integral] (emphasis mine)
A prvalue of an integer type can be converted to a prvalue of another integer type. A prvalue of an unscoped enumeration type can be converted to a prvalue of an integer type.
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 ]
这篇关于从 '(signed) -1' 到 'unsigned long' 的转换是否标准化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!