C语言端序

来源:互联网 发布:淘宝美工助手官网 编辑:程序博客网 时间:2024/05/17 07:50

C语言端序


Endianism,端序,是指用来存储数据的方法,它定义了数据类型对字节进行寻址的方式。

两种端序方式:
1、Little-endian,小端序,是将低位字节存储在内存偏移地址较低的地址中,将高位字节存储在内存偏移地址较高的地址中;
2、Big-endian,大端序,则是将低位字节存储在内存偏移地址较高的地址中,将高位字节存储在内存偏移地址较低的地址中。

比如:
0x12345678 在 big-endian 系统上的布局
内存偏移量     0     1     2     3
内存内容       0x12     0x34     0x56     0x78

0x12345678 在 little-endian 系统上的布局
内存偏移量     0     1     2     3
内存内容     0x78     0x56     0x34     0x12

机器大小端和环境相关,可以使用下面的办法判断机器的大小端:
#include <cstdlib>
#include <iostream>

using namespace std;

union test
{
    int i;
    char c;
};
   
int main()
{
    union test t;
    t.i = 0x12345678;
    if(t.c == 0x78)
        cout<<"Little-endism"<<endl;
    else
    cout<<"Big-endism"<<endl;
    system("pause");
    return 0;   
}

在获悉环境的大小端后,就可以进行细致的分析了,
比如 Little-endlism 环境下:
#include <cstdlib>
#include <iostream>

using namespace std;

union test
{
    int i;
    char c;
};
   
int main()
{
    union test t;
    t.i = 0x12345678;
    short int x= *((short int *)(&(t.c)));
    cout<<hex<<x;
    system("pause");
    return 0;   
}

0x12345678 在 little-endian 系统上的布局
内存偏移量     0     1     2     3
内存内容     0x78     0x56     0x34     0x12

short int 为2字节(32位平台下)
将访问:
内存偏移量     0     1
内存内容     0x78     0x56
所以, 最后的结果为 (0x)5678


Endianism 在以下情况中非常重要:
1.使用位掩码时
2.对象的间接指针地址部分

合理使用联合体、位域等手段,可以在一定程度避免端序问题。
原创粉丝点击