c++ - 替换方法改变 QByteArray 的大小

标签 c++ qt qbytearray

我想操作存储在 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/

相关文章:

C++ unix下递归复制目录

C++ 在数组或字符串中插入字符

c++ - 主要针对 C++ 的持续构建基础架构建议;格林希尔诚信

c++ - 在维基百科中使用哪种颜色渐变为曼德布罗着色?

c++ - 为什么 Windows 和 Linux 的标准库函数名称不同?

c++ - QGraphicsScene清晰显示

c++ - 如何调整 QMainWindow 上的窗口装饰大小?

c++ - QByteArray 的标准替代品

javascript - QByteArray 通过 QWebChannel 在 Javascript 中被视为字符串

c++ - 从 QByteArray 使用 libjpeg 加载 jpeg 图像纹理