首先我们来介绍一下大端和小端
大端模式:是指数据的高位保存在内存的低地址中,而数据的低位保存在内存的高地址中,这种存储模式有点儿类似于把数据当做字符串顺序处理:地址由小向大增加,而数据从高位往低位存放.
小端模式:是指数据的高位保存在内存的高地址中,而数据的低位保存在内存的低地址中,这种存储模式将地址的高低和数据位权有效地结合起来,高地址部分权值搞,低地址部分权值低.
介绍一个判断大小端的代码:
#include<stdio.h>
//判断编译器是大端还是小端
int main()
{
short int x;//两个字节
char x0,x1;//一个字节
x = 0x1122;
x0 = ((char *)&x)[0];//低地址单元
x1 = ((char *)&x)[1];//高地址单元
printf("x0 is 0x%x \nx1 is 0x%x \n",x0,x1);
if(x0 == 0x11)
{
printf("该编译器是大端");
}
else
{
printf("该编译器是小端");
}
return 0;
}
下面分享关于小端转换为大端的方法
// 转换8字节整型:
typedef unsigned long long UINT64;
#define ntohll(x) ( ((UINT64)x & 0xff00000000000000LL)>>56 | ((UINT64)x & 0x00ff000000000000LL)>>40 | ((UINT64)x & 0x0000ff0000000000LL)>>24 | ((UINT64)x & 0x000000ff00000000LL)>>8 | ((UINT64)x & 0x00000000ff000000LL)<<8 | ((UINT64)x & 0x0000000000ff0000LL)<<24 | ((UINT64)x & 0x000000000000ff00LL)<<40 | ((UINT64)x & 0x00000000000000ffLL)<<56 )
// 转换函数
double SwapDoubleEndian(double* pdVal)
{
UINT64 llVal = ntohll(*((UINT64*)pdVal));
return *((double*)&llVal);
}
//Int类型小端转换为大端
int EndianIntConvertLToB(int InputNum) {
int k = InputNum;
char *p = (char*)&k;
for (int i = 0; i<sizeof(k); i++) {
NSLog(@"%d",p[i]);
}
unsigned int num,num1,num2,num3,num4;
num1=(unsigned int)(*p)<<24;
num2=((unsigned int)*(p+1))<<16;
num3=((unsigned int)*(p+2))<<8;
num4=((unsigned int)*(p+3));
num=num1+num2+num3+num4;
NSLog(@"num is %d",num);
char * q = (char *)#
for (int i = 0; i<sizeof(num); i++) {
NSLog(@"%d",q[i]);
}
return num;
}