我的主页: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/
- 我的优快云博客:http://blog.youkuaiyun.com/techping
- 我的简书:http://www.jianshu.com/users/b2a36e431d5e/timeline
- 我的GitHub:https://github.com/techping
欢迎相互follow~
本文介绍了使用C语言判断机器CPU大小端模式的两种方法。第一种方法利用指针的强制类型转换,通过比较最低字节来确定。第二种方法则使用共用体,通过将整数赋值给共用体的一个成员,然后比较另一个成员的值来判断。
1102

被折叠的 条评论
为什么被折叠?



