gpt4 book ai didi

c++ - static_cast(signed) 与 std::bit_cast(signed) 之间有区别吗?

转载 作者:行者123 更新时间:2023-12-02 09:47:33 26 4
gpt4 key购买 nike

再次,关于 C++ 和有符号 -> 无符号(相同大小)转换/转换。

C++ 标准 4.7/2 规定:

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

好的,以二进制补码表示 static_caststd::bit_cast产生相同的位模式。

有什么理由static_cast<unsigned>(signed)更改补码或有符号幅度表示中的位模式?

可能是static_cast<unsigned>(signed)由于“模 2^n ...”,总是以位模式生成二进制补码表示(与 unsigned x = -1 始终生成 111..1 位模式相同)?

最佳答案

使用补码时,您会遇到偏移量为 -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.

例如,将 one's complement 中的“-0”转换为(与 8 位中的无符号 255 具有相同的位模式)使用 static_cast,在按照问题中引用的文本转换为无符号时,应产生“0”。这需要对位进行更改。

关于c++ - static_cast<unsigned>(signed) 与 std::bit_cast<unsigned>(signed) 之间有区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59352910/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com