Is the conversion from '(signed) -1' to 'unsigned long' standardized? [duplicate]

大兔子大兔子 提交于 2019-12-10 19:48:58

问题


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 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 ]




回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!