如何使用htonl实现long long 字节序的转换

今天同事问了一个关于如何将long long转换字节序,思考了一下先实现如下,经测试,好用!

#include<iostream>                                                                                                                    
#include<arpa/inet.h>

unsigned long long 
htonll(unsigned long long host)
{
        unsigned long temp_low, temp_high;
        temp_low = htonl((long)host);
        temp_high = htonl((long)(host >> 32));

        host &= 0;
        host |= temp_low;
        host <<= 32; 
        host |= temp_high;
        return host;
}

int main(void)
{
        unsigned long long host;
        host = 0xabefe3a287654321;
        std::cout << "host " << std::hex << host << std::endl;
        std::cout << "net " << std::hex << htonll(host) << std::endl;
        return 0;
}

你可能感兴趣的:(如何使用htonl实现long long 字节序的转换)