c++ - 使用符号位翻转和加法进行浮点减法

标签 c++ gcc floating-point arm cortex-m

从此题中取双减法代码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/

相关文章:

c++ - 抽象类和虚拟构造函数的替代方法

python - 数组包括来自 C++ 中的 python 的范围

c++ - 比较 2 int 是原子操作吗?

c - 如何在 Linux 中找到 C 编程语言的头文件?

lua - 为什么 Lua 算术不等于自身?

floating-point - MIPS:除法算法(IEEE-754 格式的有效数除法)对最后 4-5 位 (LSB) 给出了错误的答案

c++ - 将 Nim Anon 函数导出到 C++

C++ --> 错误 : expected ')' before 'conf'

在可执行文件中找不到 C++ 动态链接库

C++ Cout float 问题