更改一位双 [英] Changing one bit in double

查看:179
本文介绍了更改一位双的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试改变一个位,例如:



Double x: -1.500912597 这是:



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



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



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



Double x: -1.563412596999999903



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

解决方案

方式是使用 memcpy (是的,我知道你在想什么,而不是没有效率)。



请注意,此解决方案不考虑字节顺序。您也需要适应这种情况,以免严格便携。

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

//只编译此函数,如果Integer的大小与double
模板相同大小< class Integer,std :: enable_if_t< sizeof(Integer)== sizeof(double)> * = nullptr>
double or_bits(double input,Integer bits)
{
整数拷贝;

//将double转换为整数
std :: memcpy(& copy& input,sizeof(input))的一个位表示;
//执行按位操作
copy | = bits;
//将这些位转换回一个double
std :: memcpy(& input,& copy,sizeof(copy));
//返回double
返回输入;
}

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
pre>

I am trying to change one bit in a double so that for example:

Double x: -1.500912597 which is:

Binary: 10111111 11111000 00000011 10111100 11101101 01100100 01001111 10010011

Change one bit in the underlying binary code (for example, bit 16) so that:

Binary: 10111111 11111001 00000011 10111100 11101101 01100100 01001111 10010011

Double x: -1.563412596999999903

Is there some C++ code I can use for this?

解决方案

The only portable way is to use memcpy (yes, I know what you're thinking, and no it's not inefficient).

Note that this solution does not take into account byte-ordering. You'd need to cater for that too to be strictly portable.

#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;
}

assembly output on 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

这篇关于更改一位双的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆