6
votes

Again, about C++ and signed -> unsigned (same size) conversion/casting.

C++ Standard 4.7/2 states that:

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

Ok, in a two's complement representation static_cast and std::bit_cast produce the same bit pattern.

Is there any reason for static_cast<unsigned>(signed) to change bit pattern in a one's complement or signed magnitude representation?

May be static_cast<unsigned>(signed) always produce two's complement representation in bit pattern due to "modulo 2^n ..." (same as unsigned x = -1 always produce 111..1 bit pattern)?

1
bit_cast is available in C++20 only. And, in C++20, the only allowed integer representation is two's complement. I don't understand your question "Is there any reason for static_cast<unsigned>(signed) to change bit pattern in a one's complement or signed magnitude representation?". Are you asking, why does the standard mandate modulo 2^n behavior? Because, in modulo 2^n, bit pattern can change for non-two's-complement numbers. I think it makes sense to mandate modulo 2^n behavior, as it will be consistent across platforms.geza
@geza yep, bit_cast is c++20 feature, but assume it was available before. The question is: how static_cast<unsigned>(signed) will change bit pattern in case of one's complement or signed magnitude and why?ilynxy
Hmm, it is pretty straightforward. Suppose the number -1. In ones' complement, it has the representation of 1111 1110. If you cast it to unsigned, according to the modulo rule, the numeric value should become 255. But 255's representation is 1111 1111. So the representation has changed.geza
@geza Thanks! Is this correct: static_cast<unsigned>(signed) produce two's complement bit pattern for any signed number, except negative zero (for non-two's complement representation)?ilynxy
Yes, I think that's true.geza

1 Answers

0
votes

With one's complement you have the issue with offset of -1:

To within a constant (of −1), the ones' complement behaves like the negative of the original number with binary addition. However, unlike two's complement, these numbers have not seen widespread use because of issues such as the offset of −1, that negating zero results in a distinct negative zero bit pattern, less simplicity with arithmetic borrowing, etc.

For example, converting '-0' in one's complement (which has the same bit pattern as unsigned 255 in 8 bits) with static_cast, should result in '0' when converted to unsigned following the text qouted in the question. This neccesitates a change in bits.