c++ - 以 double 的形式改变一位

标签 c++ double bit

我正在尝试更改 double 中的一位,例如:

双倍 x:-1.500912597 这是:

二进制:10111111 11111000 00000011 10111100 11101101 01100100 01001111 10010011

更改底层二进制代码中的一位(例如,第 16 位)以便:

二进制:10111111 11111001 00000011 10111100 11101101 01100100 01001111 10010011

双 x:-1.563412596999999903

是否有一些 C++ 代码可以用于此目的?

最佳答案

唯一可移植的方法是使用memcpy(是的,我知道你在想什么,不,它并不低效)。

请注意,此解决方案未考虑字节顺序。您也需要满足这一点才能严格便携。

#include <cstdlib>
#include <cstring>
#include <utility>
#include <iostream>

// only compile this function if Integer is the same size as a double
template<class Integer, std::enable_if_t<sizeof(Integer) == sizeof(double)>* = nullptr>
double or_bits(double input, Integer bits)
{
  Integer copy;

  // convert the double to a bit representation in the integer 
  std::memcpy(&copy, &input, sizeof(input));
  // perform the bitwise op
  copy |= bits;
  // convert the bits back to a double
  std::memcpy(&input, &copy, sizeof(copy));
  // return the double
  return input;
}

int main()
{
  double d = 1.0;
  d = or_bits(d, 0x10ul);
  std::cout << d << std::endl;
}

gcc5.3 上的汇编输出:

double or_bits<unsigned long, (void*)0>(double, unsigned long):
    movq    %xmm0, %rax
    orq     %rdi, %rax
    movq    %rax, -8(%rsp)
    movsd   -8(%rsp), %xmm0
    ret

关于c++ - 以 double 的形式改变一位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37136667/

相关文章:

c++ - 命名空间会使 C++ 中的原型(prototype)方法过时吗?

c++ - 使用 Boost.MPI 仅同步部分 C++ vector

C++ 具有特定类型可变参数的多个函数参数

c# - 将 long 转换为 double 的精度损失有多大?

C++ 在不需要时双舍入

java - Java 中的反转位 - O(n)

c++ - 一种直接根据掩码转位的方法

c++ - Visual Studio 无法显示一些被监视的表达式

c++ - 如何在不使用 CRT 的情况下将 double 转换为字符串

c - 通过编辑数组元素的最后一位对数字进行编码