问题
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?
回答1:
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
nis 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 ]
回答2:
The commenter is correct; conversion to an unsigned integer type from any other integer type is always well-defined. If the range of the unsigned integer type is 0 to 2^N - 1, then the result of the conversion will be the original value reduced modulo 2^N. This will be the case even if (as in systems with a one's complement or sign-magnitude representation) said reduction modulo 2^N requires extra instructions.
来源:https://stackoverflow.com/questions/51294033/is-the-conversion-from-signed-1-to-unsigned-long-standardized