整理网络字节序

来源:互联网 发布:手机自动降温软件 编辑:程序博客网 时间:2024/06/07 12:28

接触网络了。所以去理解了一下,整形数字在网络中是如何传输的。

其中,ntohl,htonl,ntohs,htons。这四个是基本的库函数。但是有时候我们常常要发送float,double,和__int64的类型。

所以,去查看了一些关于他们的转换关系。基本也是和基本库函数是一样的,就是大小端问题。代码下:

转化为float类型。

float htonf(float f)

{

unsigned char *pp0p1;

if(htons(1) ==1) return f;

p =(unsigned char *)&f;

p0 =p[0];

p1 =p[1];

p[0] =p[3];

p[3] =p0;

p[1] =p[2];

p[2] =p1;

return f;

}

float ntohf(float f)

{

unsigned char *pp0p1;

if(ntohs(1) ==1) return f;

p =(unsigned char *)&f;

p0 =p[0];

p1 =p[1];

p[0] =p[3];

p[3] =p0;

p[1] =p[2];

p[2] =p1;

return f;

}或者

 (float)htonf(float){
    float floRet;
    
//    long * pSrc = (long*)&val;
//    long * pDes = (long*)&floRet;
    
    int * pSrc = (int*)&val;
    int * pDes = (int*)&floRet;
    
    pDes[0] = htonl(pSrc[0]);
    
    return floRet;
}


转化为double类型。

double htonf(double d)

{

unsigned char *pp0p1p2p3;

if(htons(1) ==1) return d;

p =(unsigned char *)&d;

p0 =p[0];

p1 =p[1];

p2 =p[2];

p3 =p[3];

p[0] =p[7];

p[7] =p0;

p[1] =p[6];

p[6] =p1;

p[2] =p[5];

p[5] =p2;

p[3] =p[4];

p[4] =p3;

return d;

}

double ntohf(double d)

{

unsigned char *pp0p1p2p3;

if(ntohs(1) ==1) return d;

p =(unsigned char *)&d;

p0 =p[0];

p1 =p[1];

p2 =p[2];

p3 =p[3];

p[0] =p[7];

p[7] =p0;

p[1] =p[6];

p[6] =p1;

p[2] =p[5];

p[5] =p2;

p[3] =p[4];

p[4] =p3;

return d;

}

或者

(double)htonf(double){
    
    double dbRet;
    
//    long * pSrc = (long*)&val;
//    long * pDes = (long*)&dbRet;
    int * pSrc = (int*)&val;
    int * pDes = (int*)&dbRet;
    
    pDes[0] = htonl(pSrc[1]);
    pDes[1] = htonl(pSrc[0]);
    
    return dbRet;
}

转化为__int64类型。

unsigned __int64hton64i(unsigned __int64 d)

{

unsigned char *pp0p1p2p3;

if(htons(1) ==1) return d;

p =(unsigned char *)&d;

p0 =p[0];

p1 =p[1];

p2 =p[2];

p3 =p[3];

p[0] =p[7];

p[7] =p0;

p[1] =p[6];

p[6] =p1;

p[2] =p[5];

p[5] =p2;

p[3] =p[4];

p[4] =p3;

return d;

}

unsigned __int64ntoh64i(unsigned __int64 d)

{

unsigned char *pp0p1p2p3;

if(ntohs(1) ==1) return d;

p =(unsigned char *)&d;

p0 =p[0];

p1 =p[1];

p2 =p[2];

p3 =p[3];

p[0] =p[7];

p[7] =p0;

p[1] =p[6];

p[6] =p1;

p[2] =p[5];

p[5] =p2;

p[3] =p[4];

p[4] =p3;

return d;

}

以上是一些转化的情况。

但是不一定是正确的,正确的改写。应该需要根据你当前系统对各类型的占用字节数来调整,但是原理是不变的(大小端)。

ps:在ios8中,系统有64位系统,int所占字节数为8位。而在以前的系统中,只有32位系统,int所占字节数就位4位

0 0
原创粉丝点击