c++将十进制存放在2个字节及多个字符中

        char用于C或C++中定义字符型变量,只占一个字节,signed char: -2^7 ~ 2^7-1,unsigned char : 0 ~ 2^8-1。 整型和字符型是互通的,他们是在内存中存储的本质是相同的,只是存储的范围不同而已,整型可以是2字节,4字节,8字节,而字符型只占1字节。

可以利用”位“操作,将十进制数放入unsigned char型数组中,demo如下:



#include <iostream>
#include<cstdio>
int main()
{
	int Data = 300;
	unsigned char cStore2Bytes[2];
	cStore2Bytes[0] = Data >> 8;
	cStore2Bytes[1] = Data;
	printf("%x", cStore2Bytes[0]);
	printf("\n");
	printf("%x\n", cStore2Bytes[1]);

	int Data1 = 500;
	unsigned char cStore4Bytes[4] = {};
	cStore4Bytes[0] = Data1 >> 24;
	cStore4Bytes[1] = Data1 >> 16;
	cStore4Bytes[2] = Data1 >> 8;
	cStore4Bytes[3] = Data1;
	printf("%x, %x, %x, %x", cStore4Bytes[0], cStore4Bytes[1], cStore4Bytes[2], cStore4Bytes[3]);

}

 关于位操作的介绍可以参考:C/C++取数据中高8位,低8位,合成新数据_hanxiaoyong_的博客-CSDN博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值