删除字节数组 : Qt 缓冲区之间的空字符 (\x00)

Remove null character (x00) in between buffer of byte array : Qt

本文关键字:字符 x00 之间 字节数 字节 数组 缓冲区 Qt 删除      更新时间:2023-10-16

我正在使用readAll()QSerialPort方法从虚拟COM端口读取数据。

我从硬件主板收到两个响应。
1. 字符串("10")确认
2.查询数据(";1395994881;1.0.0")字符串数据
作为QByteArray : 10x00;1395994881;1.0.0

我想从QByteArray中删除x00角色。

每当我尝试在我的 QByteArray 上执行任何操作时,我都会在QByteArray的第一部分执行,即 ''10 .跳过;1395994881;1.0.0的其余部分。

如果有任何方法可以从QByteArray中删除此x00字符,请指导我。

代码
QByteArray data = serial.readAll(); //("10x00;1395994881;1.0.0");

  1. 试用:QList<QByteArray> list = data.split('x00'); qDebug()<<list; // 10

  2. 试用:qDebug()<<data.remove(2, 1); //10

  3. 试用:qDebug()<<QString(data); //10

  4. 试用:qDebug()<<data.replace('x00', ""); //10

  5. 试用:Used Loop to go byte by byte, but same result

无论如何,我希望结果字符串为单个字符串或拆分。但是需要完整的字符串,例如10;1395994881;1.0.010;1395994881;1.0.0.

我还在下面提到Stack Overflow问题。
1.QByteArray to QString
2.Remove null from string:Java
3.Code Project

编辑

//Function to read data from serial port  
void ComPortThread::readData()
{
if(m_isComPortOpen) {
//Receive data from serial port
m_serial->waitForReadyRead(500); //Wait 0.5 sec
QByteArray data = m_serial->readAll();
if(!data.isEmpty()) {
qDebug()<<"Data: "<<data;  //10x00;1395994881;1.0.0
//TODO: Separate out two responce like "10" and ";1395994881;1.0.0"
//Problem : Unable to split data into two parts.
emit readyToRead(data);
}
}
}

请帮我解决这个问题。

串行端口返回的QByteArray是从原始数据创建的,其行为不像字符串。为了处理完整的数组,您可以使用 STL 样式迭代器,它对包含的NULL字符是健壮的。有关fromRawData数组的更多信息,请仔细阅读文档中的详细说明。

下面是一个肮脏的示例,显示了如何修复字符串:

const char mydata[] = {
'1', '0', 0x00, ';', '1', '3', '9', '5', '9', '9', '4', '8', '8', '1', ';', '1', '.', '0', '.', '0'
};
QByteArray data = QByteArray::fromRawData(mydata, sizeof(mydata));
qDebug() << data; // "10x00;1395994881;1.0.0"
char fixed[255];
int index = 0;
QByteArray::iterator iter = data.begin();
while(iter != data.end())
{
QChar c = *iter;
if (c != '') fixed[index++] = c.toLatin1();
iter++;
}
fixed[index] = '';
qDebug() << fixed; // 10;1395994881;1.0.0