简体   繁体   中英

Is there difference between static_cast<unsigned>(signed) vs std::bit_cast<unsigned>(signed)?

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)?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM