计算机都是以八位一个字节为存储单位,那么一个16位的整数,也就是C语言中的short,在内存中可能有两种存储顺序big-endian和litte-endian.考虑一个short整数0xAF32(0x32是低位,0xAF是高位),把它赋值给一个short变量,那么它在内存中的存储可能有如下两种情况:
大端字节(Big-endian):较高的有效字节存放在较低的存储器地址,较低的有效字节存放在较高的存储器地址。
——————————————--------
| 0x2000 | 0x2001 |
------------------------------------
| 0xAF | 0x32 |
------------------------------------
小端字节(Big-endian):字数据的高字节存储在高地址中,而字数据的低字节则存放在低地址中。
——————————————--------
| 0x2000 | 0x2001 |
------------------------------------
| 0x32 | 0xAF |
------------------------------------
/********大端返回0;小端返回0*******/ int checkCPU() { union w { int x ; char y ; }c ; c.x = 1; return (c.y==1)) }
#include<stdio.h> typedef unsigned int uint_32 ; typedef unsigned short uint_16 ; #define BSWAP_16(x) \ (uint_16)((((uint_16)(x) & 0x00ff) << 8) | \ (((uint_16)(x) & 0xff00) >> 8) \ ) #define BSWAP_32(x) \ (uint_32)((((uint_32)(x) & 0xff000000) >> 24) | \ (((uint_32)(x) & 0x00ff0000) >> 8) | \ (((uint_32)(x) & 0x0000ff00) << 8) | \ (((uint_32)(x) & 0x000000ff) << 24) \ ) uint_16 bswap_16(uint_16 x) { return (((uint_16)(x) & 0x00ff) << 8) | \ (((uint_16)(x) & 0xff00) >> 8) ; } uint_32 bswap_32(uint_32 x) { return (((uint_32)(x) & 0xff000000) >> 24) | \ (((uint_32)(x) & 0x00ff0000) >> 8) | \ (((uint_32)(x) & 0x0000ff00) << 8) | \ (((uint_32)(x) & 0x000000ff) << 24) ; } int main(int argc,char *argv[]) { printf("------------带参宏-------------\n"); printf("%#x\n",BSWAP_32(0x12345678)); printf("%#x\n",BSWAP_16(0x1234)) ; printf("------------函数调用-----------\n"); printf("%#x\n",bswap_32(0x12345678)); printf("%#x\n",bswap_16(0x1234)) ; return 0 ; }
linux编程函数:
#include <stdio.h> struct ST{ short val1; short val2; }; union U{ int val; struct ST st; }; int main(void) { int a = 0; union U u1, u2; a = 0x12345678; u1.val = a; printf("u1.val is 0x%x\n", u1.val); printf("val1 is 0x%x\n", u1.st.val1); printf("val2 is 0x%x\n", u1.st.val2); printf("after first convert is: 0x%x\n", htonl(u1.val)); u2.st.val2 = htons(u1.st.val1); u2.st.val1 = htons(u1.st.val2); printf("after second convert is: 0x%x\n", u2.val); return 0; }