我发现以下代码能够将int64_t转换为网络字节顺序。现在,我需要相反的代码,以便将网络字节顺序转换回我的小endian机器。代码是这样的。
int64_t decode(void* value){
int64_t vv = *((int64_t*) value);
int num = 42;
if(*(char *)&num == 42) //test big/little endian
return (((uint64)htonl(vv)) << 32) + htonl(vv >> 32);
else
return vv;
}非常感谢!
发布于 2013-05-04 22:38:04
您的htonll的代码
#define htonll(x) ((((uint64_t)htonl(x)) << 32) + htonl((x) >> 32))将字节首尾相接地翻转。如果应用两次,它会将值恢复到其原始状态。因此,同样的函数也可以用于ntohll。
发布于 2017-11-20 02:07:43
htonl可以通过以下步骤完成
如果它的高字节顺序系统直接返回值,则返回
对于ntohll也是如此
#define HTONLL(x) ((1==htonl(1)) ? (x) : (((uint64_t)htonl((x) & 0xFFFFFFFFUL)) << 32) | htonl((uint32_t)((x) >> 32)))
#define NTOHLL(x) ((1==ntohl(1)) ? (x) : (((uint64_t)ntohl((x) & 0xFFFFFFFFUL)) << 32) | ntohl((uint32_t)((x) >> 32)))发布于 2013-05-04 22:46:56
下面是我如何使用一个联合来做这件事。位移位的方法也会工作得很好,但我想要做得更好一点。
#include<stdlib.h>
#include<stdio.h>
union MyUnion {
int64_t i64;
int32_t i32[2];
};
int64_t htonll(int64_t hostFormatInt64)
{
MyUnion u;
u.i64 = hostFormatInt64;
int32_t temp = u.i32[0];
u.i32[0] = htonl(u.i32[1]);
u.i32[1] = htonl(temp);
return u.i64;
}
int64_t ntohll(int64_t networkFormatInt64)
{
MyUnion u;
u.i64 = networkFormatInt64;
int32_t temp = u.i32[0];
u.i32[0] = ntohl(u.i32[1]);
u.i32[1] = ntohl(temp);
return u.i64;
}
void Test(int64_t i)
{
printf("Testing value %lli\n", i);
int64_t networkI = htonll(i);
printf(" Network format is %lli (0x%llx)\n", networkI, networkI);
int64_t hostAgainI = ntohll(networkI);
printf(" Back to host again %lli (0x%llx)\n", hostAgainI, hostAgainI);
if (hostAgainI != i)
{
printf("ERROR, we didn't get the original value back!\n");
abort();
}
}
int main()
{
// A quick unit test to make sure I didn't mess anything up :)
int64_t i = 0;
while(1)
{
Test(i);
Test(-i);
i += rand();
}
return 0;
}https://stackoverflow.com/questions/16375340
复制相似问题