我对这个问题的答案有一个很大的问题在 c++ 中交换位以获得双倍
然而,这个问题或多或少是我要寻找的:我从网络收到一个双精度,我想在我的机器中正确编码它。
在我收到的情况下,我int
使用以下代码执行此代码ntohl
:
int * piData = reinterpret_cast<int*>((void*)pData);
//manage endianness of incomming network data
unsigned long ulValue = ntohl(*piData);
int iValue = static_cast<int>(ulValue);
但是如果我收到一个double
,我不知道该怎么做。
问题的答案建议这样做:
template <typename T>
void swap_endian(T& pX)
{
char& raw = reinterpret_cast<char&>(pX);
std::reverse(&raw, &raw + sizeof(T));
}
但是,如果我引用这个网站:
The ntohl() function converts the unsigned integer netlong from network byte order to host byte order.
When the two byte orders are different, this means the endian-ness of the data will be changed. When the two byte orders are the same, the data will not be changed.
相反,@GManNickG 对问题的回答总是与std::reverse
.
考虑到这个答案是错误的,我错了吗?(在字节序的网络管理范围内,ntohl
尽管在 OP 问题的标题中没有准确地说明,但它的使用暗示了这一点)。
最后:我应该将我的double
分成两部分,每部分 4 个字节,然后ntohl
在这两部分上应用函数吗?还有更多规范的解决方案吗?
C 语言中还有一个有趣的问题,主机到网络双倍?,但它限制为 32 位值。答案说由于架构差异,双打应该转换为字符串......我还将使用音频样本,我是否真的应该考虑将所有样本转换为我的数据库中的字符串?(双打来自我通过网络查询的数据库)