从此题中取双减法代码Replacing __aeabi_dsub to save space (-flto issues)并稍微调整它(对于 double 值和浮点值):
extern "C" double __aeabi_dsub(double a, double b) {
// flip top bit of 64 bit number (the sign bit)
reinterpret_cast<unsigned char *>(&b)[7] ^= 0x80; // assume little endian
return a + b;
}
extern "C" float __aeabi_fsub(float a, float b) {
// flip top bit of 32 bit number (the sign bit)
reinterpret_cast<unsigned char *>(&b)[3] ^= 0x80; // assume little endian
return a + b;
}
这些a - b
(对于double
/float
)的实现是否会破坏任何浮点代码/IEEE规范? 假设ARM Cortex-M0架构不支持浮点,由GCC编译。
最佳答案
假设 IEEE 754 浮点,这不会破坏任何代码,通过查看编译的代码很容易看出。
double dsub1(double a, double b) {
reinterpret_cast<unsigned char *>(&b)[7] ^= 0x80; // assume little endian
return a + b;
}
double dsub2(double a, double b) {
return a - b;
}
编译为
dsub1(double, double): // @dsub1(double, double)
fsub d0, d0, d1
ret
dsub2(double, double): // @dsub2(double, double)
fsub d0, d0, d1
ret
( https://godbolt.org/z/rY4h5YTqb )
正如您所看到的,即使在不允许不兼容的 FP 转换的低优化级别上,这些也是等效的。
关于c++ - 使用符号位翻转和加法进行浮点减法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76657709/