3

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?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Evan Carroll
  • 78,363
  • 46
  • 261
  • 468

2 Answers2

5

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 ]

Evan Carroll
  • 78,363
  • 46
  • 261
  • 468
llllllllll
  • 16,169
  • 4
  • 31
  • 54
4

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.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312