大端模式:就是在低地址上存数值的高位,在高地址上存数值的低位;
小端模式:就是在低地址上存数值的低位,在高地址上存数值的高位;
如下程序
#include<iostream.h> #include<stdio.h> int main() { union check { int i; char ch; }c; c.i = 1; return (c.ch == 1); /* 1 : little-endian */ /* 0 : big-endian */ }
内存地址分配中,0040102B地址上是01,四个为一个int型,地址从左向右增加,因此0X01在低地址上,所以这个x86电脑是小端模式
#include<iostream.h> #include<stdio.h> bool IsBigEndian() { int a = 0x1234; char b = *(char *)&a; //通过将int强制类型转换成char单字节,通过判断起始存储位置。即等于 取b等于a的低地址部分 if( b == 0x12) { return true; } return false; } int main() { int a; a = IsBigEndian(); printf("a = %d\n",a); return 0; }
说明不是大端,是小端
#include<iostream.h> #include<stdio.h> int main() { int a[5] = {1,2,3,4,5}; int *ptr1 = (int *)(&a+1); int *ptr2 = (int *)((int)a+1); int *ptr3 = (int *)((int)a+2); printf("%x,%x,%x,%x,%x,%x\n",a,ptr1[-1],ptr2,*ptr2,ptr3,*ptr3); return 0; }
(int)a+1的值是元素a[0]的第2个字节的地址,然后把这个地址强制转换成int * 类型的值赋给ptr2,也就是*ptr2的值是a[0]第2个字节开始的连续4个字节的内容,这里&a[0]的起始地址为0x0012ff6c
00 | 00 | 00 | 01 | 0012ff6c |
00 | 00 | 00 | 02 | 0012ff70 |
00 | 00 | 00 | 03 | 0012ff74 |
所以(int)a+1的连续四个字节的内容是02 00 00 00,输出时省略第一个0,所以为2000000
据此,(int)a+2的连续四个字节的内容是00 02 00 00,输出应为20000