编程区分CPU大小端

网友投稿 523 2022-05-29

编程区分CPU大小端

编写一段代码判断系统中的CPU是小端还是大端模式?

方法1:将一个字节的数据和一个整型数据存放于同样的内存的开始地址

方法2;union成员本身被存在相同的内存空间(共享内存)

关注我

通过读取整数数据,分析字节在整型数据的高位还是地位来判断CPU工作于小端还是大端

大端认为第一个字节是最高位字节(按照从低地址到高地址的顺序存放数据的高位字节到低位字节) 小端正相反,认为第一个字节是最低位字节(低地址到高地址存放数据的低位字节到高位字节)

1

2

一般来说X86是小端字节序(常见),PowerPC是大端

#include typedef unsigned char BYTE; int main() { unsigned int num, *p; p = # num = 0; *(BYTE *)p = 0xff; if (num == 0xff) { printf("The endian of cpu is little\n"); } else { printf("The endian of cpu is big\n"); //num = 0xff000000 } return 0; } /* The endian of cpu is little */

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

编程区分CPU大小端

24

25

#include int checkCPU() { union w { int a; char b; } c; c.a = 1; return (c.b == 1); } int main() { int is; is =checkCPU(); if (is == 1) { printf("The endian of cpu is little\n"); } else { printf("The endian of cpu is big\n"); } return 0; } /* The endian of cpu is little */

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

关注我

我的首发平台是【CodeAllen】,欢迎关注并回复“1024”进入资料群获取免费学习资料

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:AD域是什么意思?有什么用?
下一篇:【以太坊】什么是雷电网络 Raiden network
相关文章