如果有一个变量
unsigned int a=0x12345678;
大端Big-Endian:高字节在前 12 34 56 78
小端Little-Endian:低字节在前 78 56 34 12
现在在vs上来看看&a
由此可以看见我的pc是小端的(基本上可以断定)
现在的PC、服务器、嵌入式产品基本以小端为主。(以前存在大端的芯片,摩托罗拉的对讲机)
在协议中必须规定大小端,否则无法还原数据。
为什么这么说呢?还有为什么要提大端和小端的概念!
因为现在我们设备差不多都是小端的。但规定当发送网络信息的时候得采用大端
这是规定的。所以必须这么做
下面来展示下大端小端的转化
#include <stdio.h>
#include <string.h>
int toByte(unsigned int a, unsigned char *buf)
{
buf[0] = a >> 24;
buf[1] = a >> 16;
buf[2] = a >> 8;
buf[3] = a;
return 4;
}
unsigned int fromBtytes(const unsigned char *buf)
{
unsigned int result = 0;
result += buf[0] << 24;
result += buf[1] << 16;
result += buf[2] << 8;
result += buf[3];
return result;
}
int main()
{
unsigned int a = 0x12345678;
unsigned char buf[4];
toByte(a, buf);
unsigned int b = fromBtytes(buf);
return 0;
}
通过位运算就很容易把一个数据转化为大端或者小端。