最近,我创建了一个小的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
答案 0 :(得分:1)
您的代码中存在大量错误:
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();
}
由于checkSum
与MainWindow
无关,因此它应该是自由函数,而不是方法 - 甚至不是静态方法。
答案 1 :(得分:0)
我之前通过使用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;
}