gpt4 book ai didi

c++ - 将无符号转换为有符号并返回

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:30:12 27 4
gpt4 key购买 nike

我有一个无符号值需要作为有符号值传递给一个函数(它没有被函数触及)。当它出来时,我将它转换回未签名的状态。我知道强制转换为有符号的结果是在溢出时定义的实现,但我至少可以保证在强制转换回它时最终得到相同的值(就像使用函数指针一样)吗?

例子:

int32_t function_with_default(int32_t a_Default)
{
// Try some stuff
// ...

// Fall back to default
return a_Default;
}

void main()
{
uint32_t input = UINT32_MAX;
uint32_t output = static_cast<uint32_t>(function_with_default(static_cast<int32_t>(input));

// Is is guarenteed to be true?
input == output;
}

我确实保证有符号整数总是大于或等于无符号整数(以字节为单位),因此不会因空间不足而丢失数据。

最佳答案

不,你没有这样的保证:[conv.integral]

2 If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2^n 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 ]

3 If the destination type is signed, the value is unchanged if it can be represented in the destination type; otherwise, the value is implementation-defined.

关于c++ - 将无符号转换为有符号并返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41058221/

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