1. 位运算
short value=200;
char c = (value>>8)&0xff;//取高字节
char d = value& 0xff;//取低字节
将高位字节移位至short的高八位中,低字节赋值到short的低八位中。
#include <iostream>
using namespace std;
int main()
{
unsigned char a[2] = {0x55, 0xff};
short result;
result = result | a[1]; // 小端模式
result = result << 8;
result = result | a[0];
cout << result << endl; // -171
return 0;
}
2. 联合体
#include <iostream>
using namespace std;
union TwoByte
{
short _short;
unsigned char _uchar[2];
};
int main()
{
unsigned char a[2] = {0x55, 0xff};
TwoByte two_byte;
two_byte._uchar[0] = a[0]; // 小端模式
two_byte._uchar[1] = a[1];
short result = two_byte._short;
cout << result << endl; // -171
return 0;
}
3.指针
#include <iostream>
using namespace std;
int main()
{
unsigned char a[2] = {0x55, 0xff};
short result;
result = *((short *)a); // 小端模式
cout << result << endl; // -171
return 0;
}
场景:取字符串长度转为两个16进制char,使用QByteArray补足0
int len=msg.size();
QString sMsgLen=QString("%1").arg(len,4,16,QLatinChar('0'));
QByteArray lenArray;
lenArray=QByteArray::fromHex(sMsgLen.toLocal8Bit());
char lenL=lenArray.at(1);
char lenH=lenArray.at(0);