不能翻转签名

Can not flip sign

本文关键字:翻转 不能      更新时间:2023-10-16

我发现了一个奇怪的错误,当我尝试翻转数字 -9223372036854775808 的符号时,它什么也没做。我得到相同的数字,或者至少这是调试器向我显示的。有没有办法在不分支的情况下解决这个问题?

#define I64_MAX  9223372036854775807LL
#define I64_MIN  (-I64_MAX-1) 
// -9223372036854775808 (can not be a constant in code as it will turn to ull)
using i64 = long long int;
int main()
{
 i64 i = I64_MIN;
 i = -i;
 printf("%lld",i);
 return 0;
}

对 i32,i16,i8 做同样的事情。


编辑:
当前修复:
// use template??
c8* szi32(i32 num,c8* in)
{
    u32 number = S(u32,num);
    if(num < 0)
    {
        in[0] = '-';
        return SerializeU32(number,&in[1]);
    }
    else
    {
        return SerializeU32(number,in);
    }
} 

你不能以完全可移植的方式做到这一点。 与其处理int64_t,不如让我们考虑int8_t。 原理几乎完全相同,但数字更容易处理。 I8_MAX将是 127,I8_MIN将是 -128。 否定I8_MIN会得到 128,并且没有办法将其存储在 int8_t 中。

除非你有强有力的证据表明这是一个瓶颈,否则正确的答案是:

constexpr int8_t negate(int8_t i) {
    return (i==I8_MIN) ? I8_MAX : -i;
}

如果你确实有这样的证据,那么你将需要调查一些依赖于平台的代码 - 也许是某种内在的编译器,也许是一些避免条件跳转的聪明的位摆动。


编辑:可能的无分支位摆动

constexpr int8_t negate(int8_t i) {
    const auto ui = static_cast<uint8_t>(i); 
    // This will calculate the two's complement negative of ui.
    const uint8_t minus_ui = ~ui+1;
    // This will have the top bit set if, and only if, i was I8_MIN
    const uint8_t top_bit = ui & minus_ui;
    // Need to get top_bit into the 1 bit.  Either use a compiler intrinsic rotate:
    const int8_t bottom_bit = static_cast<int8_t>(rotate_left(top_bit)) & 1;
    // -or- hope that your implementation does something sensible when you
    // shift a negative number (most do).
    const int8_t arithmetic_shifted = static_cast<int8_t>(top_bit) >> 7;
    const int8_t bottom_bit = arithmetic_shifted & 1;
    // Either way, at this point, bottom_bit is 1 if and only if i was
    // I8_MIN, otherwise it is zero.
    return -(i+bottom_bit);
}

您需要分析以确定这是否真的更快。 另一种选择是将top_bit转移到进位,并使用加进位(添加一个常数零(,或者将其写入汇编程序,并使用适当的条件执行指令。