如何将十六进制字解析为填充位数组



我有一个十六进制字节,我需要将其转换为 8 位的二进制。这是我当前的代码。

if(ID == 65290)
        {
        QBitArray b(Data_0,2);
        QString z=QString::number(Data_0,2);
        if(b.isEmpty())
          {
            ui->Test->setText(z);
            m_workerThread->sendMsg(418381594,0,0,0,0,0,0,0,0);
          }
        else
          {
            if(b.testBit(0)==1)
            {
             m_workerThread->sendMsg(418381594,1,0,0,0,0,0,0,0);
             ui->Test->setText(z);
            }
          }

我的问题是当我构建数组时,它会将索引 0 填充为最高有效位。这样做的问题是每个以 1 开头的十六进制数都读取为索引 0 True。我需要有一个填充数组,该数组随十六进制输入而变化Data_0我可以按位查看位。例如:

[0|0|0|0|0|0|

0|0|0|1] 索引 0 等于 1[1|1|1|0|0|0|0|0|0] 索引 0 等于 0等。那些是键盘上的灯的代表。目前 1,2,4,8,16 都显示索引 0 为 1。

谢谢。

您不需要为此使用字符串。(请注意,"十六进制"不是一个值。它只是整数值的一种表示形式)。
示例:

quint8 a = /* some val */; // your 8-bit value
QBitArray b(8, 0); // bit array
for(int i=0; i<8; i++) // loop by each of 8 bits of your 8-bit value
{
    /* There I create the bitwise mask for
    each bit of your 8-bit value. 
    After that I apply it for the value */
    quint8 theMaskForEachBit = 1 << i; // movement by the order
    bool bit = a & theMaskForEachBit; // appyling the mask 
    b[i] = bit;
}

解释:

'<<' is the Bitwise leftshift operator:
1 << 0 is equal to 00000001
1 << 1 is equal to 00000010
...
1 << 7 is equal to 10000000
'&' is the Bitwise AND operator:
01001000 & 
10111000 = 
--------
00001000

理解C++按位运算符的好文章:http://www.cprogramming.com/tutorial/bitwise_operators.html
另请参阅:https://en.wikipedia.org/wiki/Two%27s_complement

最新更新