将int数字存到char buf中
例如: 将数字2018存到char buf[2]中
1、分析
首先2018有4个数字,而buf只有2个字节,那传统的赋值转换应该是不行了,那就要考虑用位的方式了,2018二进制为111 11100010 = 0x7e2 正好占两个字节(8位为一个字节),那果断用移位的方式来转存。
2、代码实现
#include <stdio.h>
#include <stdlib.h>
int main()
{
int angle=2018;
unsigned char buf[2];
int tem1_angle = angle;
buf[0] = (unsigned char)(tem1_angle>>8);
int tem2_angle = angle;
buf[1] = (unsigned char)((tem2_angle <<8)>>8);
printf("0x%x, 0x%x\n", buf[0], buf[1]);
return 0;
}
输出结果:0x7, 0xe2
注:本博客还没有针对大小端问题进行判断,移位的个数要根据情况而定。