4字節十六進制數據和大小端傳輸


甲方使用的后台要求“整型數據采用小端傳輸”,大部分數據是4字節十六進制,有一些是2字節十六進制。

關於大小端傳輸,簡單來說可以這樣認為。

內存中低地址存最低有效字節的形式為小端傳輸

內存中低地址存最高有效字節的形式為大端傳輸

例如一個4字節十六進制數"0x11223344",裝入QByteArray中。

按照字節左邊為高位,右邊為低位的規則。

如果取出結果如下

buff[0] == 0x44;

buff[1] == 0x33;

buff[2] == 0x22;

buff[3] == 0x11;

這里的"0"就表示低地址,0x44表示最低有效位;這樣的傳輸方式為小端傳輸

 

Qt中關於大小端數據也有封裝好的接口,頭文件qendian.h或者QtEndian

另外這個博客有更詳細的解釋和說明:

大小字節大小端

主要記錄一下進制之間的轉換

 1     int c=254254;
 2     QByteArray data((char*)&c,4);
 3     QByteArray data0=intToByte(c);
 4     QByteArray data1=QByteArray::fromHex(QString::number(c,16).toLatin1());
 5     qDebug()<<data.toHex()<<data.toHex().toInt(NULL,16)<<data.mid(0,1).toHex()<<data.mid(1,1).toHex()<<data.mid(2,1).toHex()<<data.mid(3,1).toHex();
 6     qDebug()<<data0.toHex()<<bytesToInt(data0);
 7     qDebug()<<data1.toHex()<<data1.toHex().toInt(NULL,16);
 8 
 9     const quint32 i =  1010;
10     QString hex = QString("%1").arg(i, 8, 16, QLatin1Char('0'));
11     qDebug() << "hex " << hex;
12     bool ok;
13     qDebug() << hex.toInt(&ok, 16);
14    
15     //十進制轉十六進制
16     QByteArray buffer;
17     buffer[0] = (i & 0xff);
18     buffer[1] = ((i >> 8) & 0xff);
19     buffer[2] = ((i >> 16) & 0xff);
20     buffer[3] = ((i >> 24) & 0xff);
21 
22     //十六進制轉回十進制數
23     quint32 x = (buffer[0] & 0x000000ff)
24             |   ((buffer[1] << 8 )& 0x0000ff00)
25             |   ((buffer[2] << 16)& 0x00ff0000)
26             |   ((buffer[3] << 24)& 0xff000000);
27     qDebug() << "x" << x;
28     int c = 0;
29 
30     //十六進制轉string
31     QString et;
32     while(c < 4){
33         QString str =QString("%1").arg(buffer[c]&0xFF,2,16,QLatin1Char('0'));   //2 字符寬度
34         et += str;
35         c++;
36     }
37     qDebug() << "et " << et;
38     qDebug() << et.toInt(&ok, 16);
39     qDebug() <<"ok" << ok ;
40 
41 //返回小端數據接口使用
42     uchar *ptr = new uchar[4];
43     qToLittleEndian(i,ptr);
44     int c = 0;
45     while(c < 4){
46         buffer.append(ptr[c]);
47         c++;
48     }
49 
50     qToLittleEndian(i, ptr);
51     //qbswap<quint32>(i, ptr);
52 
53     qDebug("%02x,%p",ptr[0],&ptr[0]);
54     qDebug("%02x,%p",ptr[1],&ptr[1]);
55     qDebug("%02x,%p",ptr[2],&ptr[2]);
56     qDebug("%02x,%p",ptr[3],&ptr[3]);
View Code

 

20190319 新增

今天在做解壓縮和壓縮功能,使用libz.so庫

測試代碼:

 QByteArray baSrc = "3c3f786d6c2076657273696f6e3d22312e302220656e636f64696e673d22474232333132223f3e3c726f6f743e3c6a79646d3e3430353030313c2f6a79646d3e3c736262683e39393030";
    QByteArray endSrc(baSrc.size()/2, '\0');
    for(int i = 0; i < baSrc.size(); i += 2){
        char tmp[3] = {0};
        memcpy(tmp, (uchar*)baSrc.data()+i, 2);
        endSrc[i/2] = strtol(tmp, 0 , 16);
    }

    QByteArray hexbuffer = QByteArray::fromHex(baSrc);
View Code

其中對數據流通過了兩種方式構造十六進制的QByteArray。

數據流中單獨的一個內存空間儲存的是一個字符,構造之后儲存的就是"0x3c"這樣的十六進制字符串了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM