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)?
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. – geza1111 1110
. If you cast it to unsigned, according to the modulo rule, the numeric value should become 255. But 255's representation is1111 1111
. So the representation has changed. – geza