不能翻转签名
Can not flip sign
我发现了一个奇怪的错误,当我尝试翻转数字 -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
转移到进位,并使用加进位(添加一个常数零(,或者将其写入汇编程序,并使用适当的条件执行指令。
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么我的for循环不能正确获取argv
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 为什么我不能在 FOR LOOP 中使用 i/10,C++?
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 为什么模板类中的对象不能返回值
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- ld:bind_at_load和-bitcode_bundle(Xcode设置ENABLE_bitcode=YES)不能
- 数组长度,为什么从命令行获取时不能使用它?
- Windows/Cygwin - 不能使用 pybind11 - 犯错误
- 为什么我不能使用 EGL 创建无头 OpenGl 上下文?
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- 为什么我不能将 rand() 与数组的大小一起使用?
- 为什么虚函数不能是静态的和全局的?
- 为什么我不能在 while 循环中创建线程?
- 为什么这个音频包络不能通过开关的情况?
- 不能翻转签名