Welcome to Rooeye's blog

大小端判断以及字节序转化

OJ rooeye 743℃ 0评论
大小端判断函数:

  1. //判断大小端字节序
  2. void judgeEndian()
  3. {
  4. int num = 0x01020304;
  5. char* pchar = (char*)#
  6. if(*pchar==0x01)
  7. {
  8. printf("the endian is Big-Endian\n");
  9. }else if(*pchar==0x04)
  10. {
  11. printf("the endian is little-Endian\n");
  12. }else
  13. {
  14. printf("other-Endian\n");
  15. }
  16. }
字节序转化:
  1. //改变数字num的字节序
  2. //如果是大端转化为小端
  3. //如果是小端转化为大端
  4. int changeEndian(int num)
  5. {
  6. int d = num&0xff;
  7. num>>=8;
  8. int c = num&0xff;
  9. num>>=8;
  10. int b = num&0xff;
  11. num>>=8;
  12. return (d<<24)|(c<<16)|(b<<8)|num;
  13. }
完整版测试代码:
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. //判断大小端字节序
  4. void judgeEndian()
  5. {
  6. int num = 0x01020304;
  7. char* pchar = (char*)&num;
  8. if(*pchar==0x01)
  9. {
  10. printf("the endian is Big-Endian\n");
  11. }else if(*pchar==0x04)
  12. {
  13. printf("the endian is little-Endian\n");
  14. }else
  15. {
  16. printf("other-Endian\n");
  17. }
  18. }
  19. //改变数字num的字节序
  20. //如果是大端转化为小端
  21. //如果是小端转化为大端
  22. int changeEndian(int num)
  23. {
  24. char* p = (char*)&num;
  25. int d = (*p++)&0xff;
  26. int c = (*p++)&0xff;
  27. int b = (*p++)&0xff;
  28. int a = *p;
  29. return (d<<24)|(c<<16)|(b<<8)|a;
  30. }
  31. int main()
  32. {
  33. judgeEndian();
  34. int num = 0x11223344;
  35. printf("before change endian , num = 0x%x\n",num);
  36. printf("after change endian , num = 0x%x\n",changeEndian(num));
  37. return 0;
  38. }
来自为知笔记(Wiz)

转载请注明: Jinkun 的博客 » 大小端判断以及字节序转化

喜欢 (0)
发表我的评论
取消评论

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址