主机字节序与网络字节序的转换

#include "stdafx.h"

#include <winsock2.h>
#include <windows.h>

#pragma comment(lib,"ws2_32.lib")



short myntohs(short s)
{
    BYTE high=(BYTE)s>>8;
    BYTE lower=(BYTE)s;
    s=(lower<<8)+high;
    return s;
}


short myntohs1(short s)
{
    __asm 
    {
        movzx eax,word ptr [ebp+8]
        mov ch,al
            shr ax,8
            or ah,ch
            mov s,ax
    }
    return s;
}


short _declspec(naked) myntohs2(short s)
{
    __asm 
    {
        push ebp
            mov ebp,esp

            movzx eax,word ptr [ebp+8]
        mov ch,al
            shr ax,8
            or ah,ch
            pop ebp
            ret    
    }
}

int main(int argc, char* argv[])
{
    printf("Hello World!
");
    int n= 0x12345678;
    int nMax=10000000;
    DWORD dwBegin=GetTickCount();
    for(int i=0;i<nMax;i++)
        myntohs(n);
    printf("%d
",GetTickCount()-dwBegin);
    printf("myntohs:%x
",myntohs(n));

    DWORD dwBegin1=GetTickCount();
    for(int i=0;i<nMax;i++)
        myntohs1(n);
    printf("%d
",GetTickCount()-dwBegin1);
    printf("myntohs1:%x
",myntohs1(n));

    DWORD dwBegin2=GetTickCount();
    for(int i=0;i<nMax;i++)
        myntohs2(n);
    printf("%d
",GetTickCount()-dwBegin2);
    printf("myntohs2:%x
",myntohs2(n));

    dwBegin=GetTickCount();
    for(int i=0;i<nMax;i++)
        ntohs(n);
    printf("%d
",GetTickCount()-dwBegin);
    printf("ntohs:%x
",ntohs(n));

    dwBegin=GetTickCount();
    for(int i=0;i<nMax;i++)
        htonl(n);
    printf("%d
",GetTickCount()-dwBegin);
    printf("htonl:%x
",htonl(n));
    getchar();
    return 0;
}

//int main()
//{
//    int a = 0x12345678;
//    int b = ntohs(a);
//    int c = htons(a);
//    int d = htonl(a);
//    int e = ntohl(a);
//    printf("ntohs is %x
",b);
//    printf("htons is %x
",c);
//    printf("htonl is %x
",d);
//    printf("ntohl is %x
",e);
//    getchar();
//    return 0;
//}
ntohs
htons
htonl ntohl

n = net h = host s = short l = long
原文地址:https://www.cnblogs.com/RodYang/p/3274777.html