C语言判断机器CPU大小端模式的两种方法

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

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

 

第一种方法思路:

利用指针的强制类型转换,取到低地址

#include <stdio.h>

 int main()
 {
     int a;

     a = 0x12345678;
     char *p = (char *)&a; //强制转换取到a的低地址

     printf("a  的值 0x%x, 地址 %p\n",a,&a);
     printf("p  的值 0x%x,       地址 %p\n",*p,p);
     printf("p+1的值 0x%x,       地址 %p\n",*(p+1),p+1);
     printf("p+2的值 0x%x,       地址 %p\n",*(p+2),p+2);
     printf("p+3的值 0x%x,       地址 %p\n",*(p+3),p+3);

/*******************************************
 * a  的值 0x12345678, 地址 0x7ffef061833c
 * p  的值 0x78,       地址 0x7ffef061833c
 * p+1的值 0x56,       地址 0x7ffef061833d
 * p+2的值 0x34,       地址 0x7ffef061833e
 * p+3的值 0x12,       地址 0x7ffef061833f
 * little endian
 *
 *******************************************/

     if (*p == 0x78) {    //低地址 存 低字节数据
         printf("little endian\n");
     }
     else if (*p == 0x12) {
         printf("big endian\n");
     }
     return 0;
 }

第二种方法思路:

利用共用体所有数据都从同一地址开始存储,从低位地址开始存储。

#include <stdio.h>

union test_union
{
    int a;
    char b[4];
} test;

int main()
{
    test.a = 0x12345678;

    printf("test.a   的值 0x%x, 地址 %p\n",test.a,&test.a); //联合体变量的各个成员都是从 低地址 开始公用的
    printf("test.b[0]的值 0x%x, 地址 %p\n",test.b[0],&test.b[0]); //&test.b[0]是test.a的低地址
    printf("test.b[1]的值 0x%x, 地址 %p\n",test.b[1],&test.b[1]);
    printf("test.b[2]的值 0x%x, 地址 %p\n",test.b[2],&test.b[2]);
    printf("test.b[3]的值 0x%x, 地址 %p\n",test.b[3],&test.b[3]);

/*******************************************
 * 打印结果:
 * test.a   的值 0x12345678, 地址 0x55d37ac0f014
 * test.b[0]的值 0x78, 地址 0x55d37ac0f014
 * test.b[1]的值 0x56, 地址 0x55d37ac0f015
 * test.b[2]的值 0x34, 地址 0x55d37ac0f016
 * test.b[3]的值 0x12, 地址 0x55d37ac0f017
 * little endian
 *
 *******************************************/

    if (test.b[0] == 0x78) {    //test.a的低地址 存储的是0x78
        printf("little endian\n");
    }
    else if (test.b[0] == 0x12){
        printf("big endian\n");
    }
    return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值