您的位置:首页 > 编程语言 > C语言/C++

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

2016-12-10 17:12 369 查看
我的主页:http://www.techping.cn/

这个.cn域名随时都可能停用,如有更新,我会说明。

我的个人站点博客:http://www.techping.cn/blog/wordpress/

我的简书:http://www.jianshu.com/users/b2a36e431d5e/timeline

我的Github地址:https://github.com/ChenZiping

欢迎相互follow~—

我的主页:http://www.techping.cn/

这个.cn域名随时都可能停用,如有更新,我会说明。

我的个人站点博客:http://www.techping.cn/blog/wordpress/

我的简书:http://www.jianshu.com/users/b2a36e431d5e/timeline

我的Github地址:https://github.com/ChenZiping

欢迎相互follow~# C语言判断机器CPU大小端模式的两种方法

本文介绍使用C语言编写程序判断机器CPU大小端模式的两种方法。

第一种方法

思路:利用指针的强制类型转换

#include <stdio.h>

int main()
{
int a = 0x12345678;
char *p = (char *)&a;//强制转换取到a最低字节的地址
if (*p == 0x78) {
//a  12 34 56 78(Hex)
//*p          78
printf("little endian\n");
}
else if (*p == 0x12) {
//a  78 56 34 12(Hex)
//*p          12
printf("big endian\n");
}
return 0;
}


第二种方法

思路:利用共用体所有数据都从同一地址开始存储。

#include <stdio.h>

union test_union//用于测试的共用体
{
int a;//元素a,占4个字节
char b;//元素b,占1个字节,b在内存中的地址为a最低字节的地址
} test;

int main()
{
test.a = 0x12345678;
if (test.b == 0x78) {
//test.a 12 34 56 78(Hex)
//test.b          78
//b在内存中的地址为a最低字节的地址
printf("little endian\n");
}
else if (test.b == 0x12) {
//test.a 78 56 34 12(Hex)
//test.b          12
//b在内存中的地址为a最低字节的地址
printf("big endian\n");
}
return 0;
}


我的个人主页:http://www.techping.cn/

我的个人站点博客:http://www.techping.cn/blog/wordpress/

我的CSDN博客:http://blog.csdn.net/techping

我的简书:http://www.jianshu.com/users/b2a36e431d5e/timeline

我的GitHub:https://github.com/techping

欢迎相互follow~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息