如何在C++中的big-endian和little-endian值之间进行转换?
编辑:为清楚起见,我必须将二进制数据(双精度浮点值和32位和64位整数)从一个CPU架构转换为另一个CPU架构.这不涉及网络,因此ntoh()和类似的功能在这里不起作用.
编辑#2:我接受的答案直接适用于我正在编制的编译器(这就是我选择它的原因).但是,这里有其他非常好的,更便携的答案.
是否有一行宏定义来确定机器的字节顺序.我使用以下代码,但将其转换为宏将太长.
unsigned char test_endian( void )
{
int test_var = 1;
unsigned char test_endian* = (unsigned char*)&test_var;
return (test_endian[0] == NULL);
}
Run Code Online (Sandbox Code Playgroud) 我正在研究memcache协议的实现,在某些点上,它使用64位整数值.这些值必须以"网络字节顺序"存储.
我希望有一些uint64_t htonll(uint64_t value)功能可以进行更改,但不幸的是,如果它存在,我找不到它.
所以我有1或2个问题:
我想到了一个基本的实现,但我不知道如何在编译时检查字节序以使代码可移植.所以你的帮助非常受欢迎;)
谢谢.
这是我写的最终解决方案,感谢Brian的解决方案.
uint64_t htonll(uint64_t value)
{
// The answer is 42
static const int num = 42;
// Check the endianness
if (*reinterpret_cast<const char*>(&num) == num)
{
const uint32_t high_part = htonl(static_cast<uint32_t>(value >> 32));
const uint32_t low_part = htonl(static_cast<uint32_t>(value & 0xFFFFFFFFLL));
return (static_cast<uint64_t>(low_part) << 32) | high_part;
} else
{
return value;
}
}
Run Code Online (Sandbox Code Playgroud) 是否可以将整个结构写入文件
例:
struct date {
char day[80];
int month;
int year;
};
Run Code Online (Sandbox Code Playgroud) endianness ×3
c ×2
c++ ×2
64-bit ×1
architecture ×1
file-io ×1
htonl ×1
macros ×1
portability ×1
structure ×1