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博客