从'(signed) -1'到'unsigned long'的转换是否标准化?
Is the conversion from '(signed) -1' to 'unsigned long' standardized?
在, you can find 中:
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).
我知道你可以用其他方式来代表 -1
除了 Two's Compliment,这是一个有效的补充,应该在我的回答中。但是,在这样的实现中,依赖到 ULONG_MAX
的转换是否安全?
评论者正确;从任何其他整数类型到无符号整数类型的转换始终是明确定义的。如果无符号整数类型的范围是 0 到 2^N - 1,那么转换的结果将是原始值减模 2^N。即使(如在具有一个补码或符号幅度表示的系统中)所说的约简模 2^N 需要额外的指令,情况也是如此。
是的,无论实际表示如何,都可以保证:
[conv.integral](强调我的)
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 ]
在
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).
我知道你可以用其他方式来代表 -1
除了 Two's Compliment,这是一个有效的补充,应该在我的回答中。但是,在这样的实现中,依赖到 ULONG_MAX
的转换是否安全?
评论者正确;从任何其他整数类型到无符号整数类型的转换始终是明确定义的。如果无符号整数类型的范围是 0 到 2^N - 1,那么转换的结果将是原始值减模 2^N。即使(如在具有一个补码或符号幅度表示的系统中)所说的约简模 2^N 需要额外的指令,情况也是如此。
是的,无论实际表示如何,都可以保证:
[conv.integral](强调我的)
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 ]