gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:37:36 25 4
gpt4 key购买 nike

我正在尝试更改 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com