您的位置:首页 > 理论基础 > 计算机网络

Unix 网络编程基础----网络字节序(大端小端)

2015-08-16 21:12 555 查看

什么是字节序?

内存中多字节值在内存中的存储方式

考虑一个16位整数
0x1122
,由两个字节组成,其在内存中有两种存储方法:



网际协议使用大端字节序传送多字节整数

主机字节序判断方法

1. 使用union:

[code]#include<iostream>

using namespace std;

int main()
{
    union {
        short s;
        char c[sizeof(short)];
    } un;

    un.s = 0x1122;

    if(sizeof(short) == 2)
    {
        if(un.c[0] == 0x11 && un.c[1] == 0x22)
            cout << "Big Endian" << endl;
        else if(un.c[0] == 0x22 && un.c[1] == 0x11)
            cout << "Little Endian" << endl;
        else
            cout << "unknown" << endl;

    }
    //c[0]为低地址,c[1]为高地址,11为高八位,22为低八位

    else
        cout << "short size: " << sizeof(short) << endl;

    return 0;
}


ubuntu15.04,64位中输出为

Little Endian


2. 使用指针的强制类型转换

[code]#include<iostream>
#include<iomanip>
using namespace std;

template<typename t> void showBytes(t &x)
{
    int len = sizeof(t);
    unsigned char* ptr = reinterpret_cast<unsigned char*>(&x);
    //cout << len << endl;
    cout << "0x";
    for(int i(0); i != len; ++i)
    {
        cout << setw(2) << setfill('0') 
             << hex << static_cast<int>(ptr[i]) << flush;
    }
    cout << endl;
}

int main()
{
    short val = 0x1122;
    showBytes(val);
    return 0;
}


同样在本机的系统中,输出
0x2211
,说明低位在前,高位在后,即本机为小端字节序
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: