判断系统是大端还是小端

版权声明:本文为博主原创文章,转载请注明出处-- https://blog.csdn.net/qq_38790716/article/details/84930081

大端与小端

大端模式:指数据的高字节保存在内存的低地址中,低字节保存在高地址中
小端模式:指数据的高字节保存在内存的高地址中,低字节保存在低地址中

判断大端、小端的三种方式

直接观察变量的内存值

#include <iostream>
using namespace std;

int main()
{
        short a = 0x3839;
        char *p = (char *)&a;
        printf("%x\n%x\n", p[0], p[1]);
        return 0;
}

运行结果如下图(ubuntu 18.04LTS):
在这里插入图片描述

在源程序中,我们输入的是0x3839,39对应低地址,存到了p[0]中、为低字节,所以测试的系统为小端

强制转换:将&int转换为char*

#include <iostream>
using namespace std;

int main()
{
        int a = 1;
        if (*(char *)&a == 1)
                cout << "small endian." << endl;
        else
                cout << "big endian." << endl;
        return 0;
}

运行结果如下图(ubuntu 18.04LTS):
在这里插入图片描述

在源程序中,将&int强制转换成了char *,则该指针指向的是a的低地址,若指向0x01则说明为小端,否则为大端

使用联合体union进行判断

#include <iostream>
using namespace std;
union TEST {
        int a;
        char b;
};
int main(int argc, char *argv[])
{
        TEST test;
        test.a = 1;
        if (test.b == 1)
        {
                cout << "small endian." << endl;
        }
        else
        {
                cout << "big endian." << endl;
        }
        return 0;
}

运行结果如下图(ubuntu 18.04LTS):
在这里插入图片描述

---------------------------------------简单表格分析-------------------------------------------

					表1-1 0x1234abcd分别在大端与小端的内存地址增长方向
地址 big endian small endian
0x0000 0x12 0xcd
0x0001 0x34 0xab
0x0002 0xab 0x34
0x0003 0xcd 0x12

猜你喜欢

转载自blog.csdn.net/qq_38790716/article/details/84930081