C/C++之大端小端

如果有一个变量

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;
}

通过位运算就很容易把一个数据转化为大端或者小端。


评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT1995

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值