char 转换 unsigned short
场景:怎么将unsigned short (36294) 转换成unsigned char
如何将unsigned short (36294) 转换成unsigned char
我有一个unsigned short 的usdata = 36294值,十六进制为0x8DC6,想转成unsigned char 存到我的vector<unsigned char> usData里去,存进去为两个字节,即usData[0] = 0x8D,usData[1] = 0xc6.
该怎么存进去啊,求解答,新手感激不尽!!!
------解决方案--------------------
确定一个字节是8位的话:
usData[0] = usdata >> 8;
usData[1] = usdata & 0xFF;
------解决方案--------------------
------解决方案--------------------
#include <iostream>
#include <stdio.h>
#include <vector>
using namespace std;
int main()
{
unsigned short usdata = 36294;
printf("usdata: %X\n", usdata);
vector<unsigned char> vcdata;
vcdata.push_back(usdata & 0xFF); // 取usdata的低字节
vcdata.push_back((usdata >> 8) & 0xFF); // 取usdata的高字节
for (int i = 0; i < vcdata.size(); ++i)
printf("%X", vcdata[i]);
return 0;
}
如何将unsigned short (36294) 转换成unsigned char
我有一个unsigned short 的usdata = 36294值,十六进制为0x8DC6,想转成unsigned char 存到我的vector<unsigned char> usData里去,存进去为两个字节,即usData[0] = 0x8D,usData[1] = 0xc6.
该怎么存进去啊,求解答,新手感激不尽!!!
------解决方案--------------------
确定一个字节是8位的话:
usData[0] = usdata >> 8;
usData[1] = usdata & 0xFF;
------解决方案--------------------
#include <iostream>
#include<stdio.h>
#include<vector>
using namespace std;
int main(void)
{
unsigned short usdata = 36294;
printf("usdata: %X\n", usdata);
vector<unsigned char> usData;
usData.push_back(usdata >> 8);
usData.push_back(usdata % 1024);// 2的8次方
printf("usData[0]:%x\n", usData[0]);
printf("usData[2]:%x\n", usData[1]);
return 0;
}
------解决方案--------------------
#include <iostream>
#include <stdio.h>
#include <vector>
using namespace std;
int main()
{
unsigned short usdata = 36294;
printf("usdata: %X\n", usdata);
vector<unsigned char> vcdata;
vcdata.push_back(usdata & 0xFF); // 取usdata的低字节
vcdata.push_back((usdata >> 8) & 0xFF); // 取usdata的高字节
for (int i = 0; i < vcdata.size(); ++i)
printf("%X", vcdata[i]);
return 0;
}