电竞比分网-中国电竞赛事及体育赛事平台

分享

htonl、ntohl、htons、ntohs函數(shù)實現(xiàn)

 牛人的尾巴 2018-09-12

htonl、ntohl、htons、ntohs函數(shù)實現(xiàn)

2012年02月24日 12:15:25 閱讀數(shù):14216 標簽: 網(wǎng)絡 更多

typedef unsigned short int uint16;

typedef unsigned long int uint32;

 

// 短整型大小端互換

#define BigLittleSwap16(A)  ((((uint16)(A) & 0xff00) >> 8) | \

                            (((uint16)(A) & 0x00ff) << 8))

 // 長整型大小端互換

 

#define BigLittleSwap32(A)  ((((uint32)(A) & 0xff000000) >> 24) | \

                            (((uint32)(A) & 0x00ff0000) >> 8) | \

                            (((uint32)(A) & 0x0000ff00) << 8) | \

                            (((uint32)(A) & 0x000000ff) << 24))


 // 本機大端返回1,小端返回0

int checkCPUendian()

{

       union{

              unsigned long int i;

              unsigned char s[4];

       }c;

 

       c.i = 0x12345678;

       return (0x12 == c.s[0]);

}

 

// 模擬htonl函數(shù),本機字節(jié)序轉(zhuǎn)網(wǎng)絡字節(jié)序

unsigned long int t_htonl(unsigned long int h)

{

       // 若本機為大端,與網(wǎng)絡字節(jié)序同,直接返回

       // 若本機為小端,轉(zhuǎn)換成大端再返回

       return checkCPUendian() ? h : BigLittleSwap32(h);

}

 

// 模擬ntohl函數(shù),網(wǎng)絡字節(jié)序轉(zhuǎn)本機字節(jié)序

unsigned long int t_ntohl(unsigned long int n)

{

       // 若本機為大端,與網(wǎng)絡字節(jié)序同,直接返回

       // 若本機為小端,網(wǎng)絡數(shù)據(jù)轉(zhuǎn)換成小端再返回

       return checkCPUendian() ? n : BigLittleSwap32(n);

}

 

// 模擬htons函數(shù),本機字節(jié)序轉(zhuǎn)網(wǎng)絡字節(jié)序

unsigned short int t_htons(unsigned short int h)

{

       // 若本機為大端,與網(wǎng)絡字節(jié)序同,直接返回

       // 若本機為小端,轉(zhuǎn)換成大端再返回

       return checkCPUendian() ? h : BigLittleSwap16(h);

}

 

// 模擬ntohs函數(shù),網(wǎng)絡字節(jié)序轉(zhuǎn)本機字節(jié)序

unsigned short int t_ntohs(unsigned short int n)

{

       // 若本機為大端,與網(wǎng)絡字節(jié)序同,直接返回

       // 若本機為小端,網(wǎng)絡數(shù)據(jù)轉(zhuǎn)換成小端再返回

       return checkCPUendian() ? n : BigLittleSwap16(n);

}

    本站是提供個人知識管理的網(wǎng)絡存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多