使用 QByteArray 时 XOR 的输出出错

XOR gone wrong with its output when using a QByteArray

最近,我创建了一个小的 XOR 校验和,据称它有效(或者至少在我的脑海中有效)。我不知道我做错了什么,因为我遵循的逻辑与我在 C#/Java.

中使用的逻辑完全相同

目前,当整数为有符号时,它会输出垃圾值,例如 -87、-88,而当无符号时,则输出 2287800、3485000。发生这种情况是否有特殊原因?

输入数据:

QByteArray str;

    str[0] =0xAA;
    str[1] =0xBB;
    str[2] =0xCC;
    str[3] =0xDD;
    str[4] =0xFF;
    str[5] =0x00;
    char ch = checkSum(str).data()[0];
    str[6] = ch; 
    serial.write(str, 7);

checkSum 描述如下:

QByteArray MainWindow::checkSum(QByteArray &b)
{
    qint16 b_len = b.length();
    printf("b_length = %d\n", b_len);

    char val = 0x00;

    for (
       int i = 0 ; i < b_len ; i ++ ){
       val ^=  b[i];
       printf("Current: %d %d\n", val, b[i]);
    }

    return b;
}

一些输出:

b_length = 6
Current: -88 1939120
Current: -81 1939120
Current: -80 1939120
Current: -69 1939120
Current: -70 1939120
Current: -70 1939120

我前段时间通过使用 for each 并将输出更改为 char 解决了这个问题。

char MainWindow::checkSum(QByteArray &b)
{
    qint16 b_len = b.length();
    printf("b_length = %d\n", b_len);

    char val = 0x00;
    char i;
    foreach (i, b)
    {
       val ^= i;
      // printf("Current: %x %x\n", val, b);
    }

    return val;
}

您的代码中有很多错误:

char ch = checkSum(str).data()[0];
                // checkSum doesn't actually return any checksum.

QByteArray checkSum(QByteArray &b)
   // You should be returning a char, not a QByteArray.
   // You also should be taking a const reference to QByteArray.
{
    qint16 b_len = b.length();        // You're truncating the length here.
    printf("b_length = %d\n", b_len); // Perhaps you should use qDebug() instead, but it's OK as quint16 is passed to printf as an int.

    char val = 0x00;                  // OK

    for (int i = 0 ; i < b_len ; i ++ ) {
       val ^=  b[i];                  // OK
       printf("Current: %d %d\n", val, b[i]);
                                      // You're passing a `QCharRef` where an int is expected.
                                      // That's the pitfall of using non-typesafe
                                      // printf. It'd have worked with qDebug()!
    }                  

    return b;                         // You're returning the wrong thing.
}

我会这样写:

#include <initializer_list>

char checkSum(const QByteArray &data)
{
   char sum = 0x00;
   for (char c : data) {
      sum ^= c;
      qDebug() << "Current:" << (int)sum << (int)c;
   }
   return sum;
}

// This hopefully won't be necessary in a future Qt version.
QByteArray makeByteArray(std::initializer_list<uint8_t> in) {
   return QByteArray(reinterpret_cast<const char*>(in.begin()), in.size());
}

int main() {
   auto str = makeByteArray({0xAA, 0xBB, 0xCC, 0xDD, 0xFF, 0x00});
   str.append(checkSum(str));
   qDebug() << str.toHex();
}

由于checkSumMainWindow无关,它应该是一个自由函数,而不是方法——甚至不是静态方法。