我想操作存储在 QByteArray 中的 32 位写入命令。但让我感到困惑的是,我的 QByteArray 改变了大小,我无法弄清楚为什么会这样。
我的代码:
const char CMREFCTL[] = {0x85,0x00,0x00,0x0B};
QByteArray test = QByteArray::fromRawData(CMREFCTL, sizeof(CMREFCTL));
qDebug()<<test.toHex();
const char last1 = 0x0B;
const char last2 = 0x0A;
test.replace(3,1,&last2);
qDebug()<<test.toHex();
test.replace(3,1,&last1);
qDebug()<<test.toHex();
生成:
"0x8500000b"
"0x8500000a0ba86789"
"0x8500000ba867890ba86789"
我期望得到以下输出:
"0x8500000b"
"0x8500000a"
"0x8500000b"
使用 test.replace(3,1,&last2,1) 有效,但我不明白为什么我上面的代码没有给出相同的结果。
最好的问候!
最佳答案
这里是相关方法的文档:
QByteArray & QByteArray::replace ( int pos, int len, const char * after )
This is an overloaded function.
Replaces len bytes from index position pos with the zero terminated string after.
Notice: this can change the length of the byte array.
您没有为字节数组提供一个以零结尾的字符串,而是一个指向单个字符的指针。因此它将在内存中从该指针向前扫描,直到它到达 0,并将所有内存视为要替换的字符串。
如果你只想改变一个字符 test[3] = last2;
应该做你想做的。
关于c++ - 替换方法改变 QByteArray 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23362852/