在c ++中交换位为double

hid*_*yat 4 c++ floating-point double bits endianness

我试图从双尾端变为小尾端.一种方法是使用

double val, tmp = 5.55;

((unsigned int *)&val)[0] = ntohl(((unsigned int *)&tmp)[1]);
((unsigned int *)&val)[1] = ntohl(((unsigned int *)&tmp)[0]);
Run Code Online (Sandbox Code Playgroud)

但后来我收到一个警告:"解除引用类型惩罚指针将破坏严格别名规则",我不想关闭此警告.

另一种方法是:

#define ntohll(x) ( ( (uint64_t)(ntohl( (uint32_t)((x << 32) >> 32) )) << 32) | ntohl( ((uint32_t)(x >> 32)) ) ) 

val = (double)bswap_64(unsigned long long(tmp)); //or
val = (double)ntohll(unsigned long long(tmp));
Run Code Online (Sandbox Code Playgroud)

但后来失去了小数.任何人都知道在不使用for循环的情况下交换双位的好方法吗?

GMa*_*ckG 9

我可能会尝试这样的事情:

template <typename T>
void swap_endian(T& pX)
{
    // should static assert that T is a POD

    char& raw = reinterpret_cast<char&>(pX);
    std::reverse(&raw, &raw + sizeof(T));
}
Run Code Online (Sandbox Code Playgroud)

短而甜(并且相对未经测试).编译器将进行所有必要的优化.以上是针对任何POD类型定义的,并且不依赖于任何实现细节.

副本版本,用于不想修改参数时:

template <typename T>
T swap_endian_copy(T pX)
{
    swap_endian(pX);
    return pX;
}
Run Code Online (Sandbox Code Playgroud)