網路位元組序轉換函式(64位)
在網路程式設計裡,網路位元組序是big-endian的,而大部分的PC的系統都是X86處理器系列,X86採用的是little-endian,所以需要將
網路資料流轉換成本地資料流的話,需要進行位元組序的轉換。
標準庫裡提供了hlton()和nthl()兩個函式來支援轉換。
hston(unsigned short), hlton(unsigned long) 將本地位元組序轉換為網路位元組序
ntohl(unsigned long), ntohs(unsigned short) 將網路位元組序轉換為本地位元組序
但是對於64位的整數進行轉換,標準庫並沒有提供相應的轉換函式,本文將給出個人原創的64位位元組序轉換函式。
#ifndef ULONG64
#define unsigned long long ULONG64
#endif
// host long 64 to network
ULONG64 hl64ton(ULONG64 host)
{
ULONG64 ret = 0;
ULONG high,low;
low = host & 0xFFFFFFFF;
high = (host >> 32) & 0xFFFFFFFF;
low = htonl(low);
high = htonl(high);
ret = low;
ret <<= 32;
ret |= high;
return ret;
}
//network to host long 64
ULONG64 ntohl64(ULONG64 host)
{
ULONG64 ret = 0;
ULONG high,low;
low = host & 0xFFFFFFFF;
high = (host >> 32) & 0xFFFFFFFF;
low = ntohl(low);
high = ntohl(high);
ret = low;
ret <<= 32;
ret |= high;
return ret;
}
關於little endian和big endian的詳細資訊,網上的資料太多了,本文就不詳述了。