以下是我將如何使用聯合使用它。移位方法也可以很好地工作,但恕我直言,要正確地處理一點點技巧。
#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;
}
只是做同樣的,但方向相反。 – 2013-05-04 14:28:17
@JoachimPileborg:爲什麼不直接說「做相反的事情」?從邏輯意義上說,「相同但相反」到底是什麼? – 2013-05-04 14:31:15
'int64_t vv = *((int64_t *)value-> first);'是sooooo錯誤的原因很多!即使編譯正確,這段代碼也不可能做你想要的* mixed endian *系統。只需使用'printf(「%lld」,...);'...... – Sebivor 2013-05-04 15:12:12