为什么会有大小端模式之分
在计算机系统中,以字节为单位寻址,每个地址单元都对应着一个字节,一个字节为8bit。
但是在C语言中除了8bit的char之外,还有16bit的short型,32bit的int型。另外,对于位数大于8位的处理器,例如16位或者32位的处理器,由于寄存器宽度大于一个字节,那么必然存在着一个如果将多个字节安排的问题。因此就导致了大端存储模式和小端存储模式。
例如一个16bit的short型x,在内存中的地址为0x0010,x的值为0x1122,那么0x11为高字节,0x22为低字节。
对于大端模式,就将0x11放在低地址中,即0x0010中,0x22放在高地址中,即0x0011中。小端模式,刚好相反。
什么是大端和小端
大端模式:是指数据的高字节保存在内存的低地址中,而数据的低字节保存在内存的高地址中。
小端模式:是指数据的高字节保存在内存的高地址中,而数据的低字节保存在内存的低地址中。
C++ 验证大小端
#include <iostream>
using namespace std;
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
unsigned short v = 0x0102;
unsigned char *p = (unsigned char *)&v;
if (*p == 0x01)
cout << "Big" << endl;
else if (*p == 0x02)
cout << "Small" << endl;
return 0;
}
#include <iostream>
using namespace std;
typedef union uEndianTest {
struct {
bool flittle_endian;
bool fill[3];
};
char value;
} EndianTest;
static const EndianTest __Endian_Test__ = { (char)1 };
const bool platform_little_endian = __Endian_Test__.flittle_endian;
int main() {
bool* ret = const_cast<bool *>(&platform_little_endian);
cout << *ret << endl;
return 0;
}