1. 程式人生 > >Qt下正確在QByteArray中儲存位元組資料的方法

Qt下正確在QByteArray中儲存位元組資料的方法

示例程式碼:

QByteArray a;
a.resize(3);
byte b=0xfF;
a[1]=b;
qDebug("a[1]is X%",a[1]);
qDebug("a[1]is %d",QVariant(a[1]).toUInt());
qDebug("a.at(1)is X%",a.at(1));
qDebug("a.at(1)is %d",QVariant(a.at(1)).toUInt());
if(a.at(1)==255)
{
    qDebug("A");
}
if(a.at(1)==0xff)
{
    qDebug("B");
}
if(a[1]==255)
{
    qDebug("C");
}
if(a[1]==0xff)
{
    qDebug("D");
}
qDebug("sizeofbyte is %d",sizeof(a.at(1)));
qDebug()<<QVariant(a.at(1));
qDebug()<<QVariant(a[1]);

執行結果:

a[1]is X%
a[1]is -1
a.at(1)is X%
a.at(1)is -1
C
D
sizeofbyte is 1
QVariant(int, -1)
QVariant(int, -1)

由此可見要正確儲存8位無符號數(位元組資料),可以採用"array[2]=0xff"這樣的方法

要判斷其數值可以採用“if(array[2]==255)”或“if(array[2]==0xff)”這樣的方法。

至於array.at(2),靠邊歇著,苦於不知道Qt下如何輸出一個量的二進位制形式,不然就可以知道array.at(2)儲存的到底是個什麼了