我们的目的是要将一个QByteArray
数组中的四个字节合并成一个32位的无符号整数(quint32
)或有符号整数(qint32)。假设将arr
中的四个字节分别设置为0xF1
, 0xF2
, 0xF3
,和 0xF4,我们要拼出一个无符号数0xF1F2F3F4。
代码1
void MainWindow::test()
{
QByteArray arr;
arr.resize(4);
arr[0]=0xF1;
arr[1]=0xF2;
arr[2]=0xF3;
arr[3]=0xF4;
qint8 A1 = arr.at(0);
qint8 A2 = arr.at(1);
qint8 A3 = arr.at(2);
qint8 A4 = arr.at(3);
quint32 IA1 = quint32(A1<<24);
quint32 IA2 = quint32(A2<<16);
quint32 IA3 = quint32(A3<<8);
quint32 IA4 = quint32(A4);
quint32 value = (IA1 | IA2 | IA3 | IA4);
qDebug()<<value;
}
上面的代码是错误示范,得到的结果是0xFFFFFFF4。调试结果如下:
代码2
void MainWindow::test1()
{
QByteArray arr;
arr.resize(4);
arr[0]=0xF1;
arr[1]=0xF2;
arr[2]=0xF3;
arr[3]=0xF4;
quint8 A1 = static_cast<quint8>(arr.at(0));
quint8 A2 = static_cast<quint8>(arr.at(1));
quint8 A3 = static_cast<quint8>(arr.at(2));
quint8 A4 = static_cast<quint8>(arr.at(3));
quint32 IA1 = quint32(A1<<24);
quint32 IA2 = quint32(A2<<16);
quint32 IA3 = quint32(A3<<8);
quint32 IA4 = quint32(A4);
quint32 value = (IA1 | IA2 | IA3 | IA4);
qDebug()<<value;
}
上面的代码得到的结果是0xF1F2F3F4
。调试结果如下:
总结
在字节移位操作时,要将其强制转换位unsigned char类型,即按无符号数据进行移位操作。
扩展
如果我们最后需要的是一个有符号数,则完成移位操作和拼接过程后再强制转为有符号类型就可以啦。
代码3
void MainWindow::test2()
{
QByteArray arr;
arr.resize(4);
arr[0]=0xF1;
arr[1]=0xF2;
arr[2]=0xF3;
arr[3]=0xF4;
quint8 A1 = static_cast<quint8>(arr.at(0));
quint8 A2 = static_cast<quint8>(arr.at(1));
quint8 A3 = static_cast<quint8>(arr.at(2));
quint8 A4 = static_cast<quint8>(arr.at(3));
quint32 IA1 = quint32(A1<<24);
quint32 IA2 = quint32(A2<<16);
quint32 IA3 = quint32(A3<<8);
quint32 IA4 = quint32(A4);
quint32 value = (IA1 | IA2 | IA3 | IA4);
qint32 value2 = static_cast<qint32>(value);//int
qDebug()<<value;
qDebug()<<value2;
}
调试结果如下: