I am using readAll()
method of QSerialPort
class to read data from the virtual COM port.
I am getting two response from my hardware board.
1. Acknowledgement ("10")
string
2. Query Data (";1395994881;1.0.0")
string data
as a QByteArray : 10\x00;1395994881;1.0.0
I want to remove \x00
character from my QByteArray
.
Whenever I am trying to perform any operation on my QByteArray, I will perform on first part of the QByteArray
and that is ``10 . Remaining part is skipped that is ;1395994881;1.0.0
.
Please guide me if there is any way to remove this \x00
character from QByteArray
.
Code
QByteArray data = serial.readAll(); //("10\x00;1395994881;1.0.0");
Try out:
QList<QByteArray> list = data.split('\x00');
qDebug()<<list; // 10
Try out:
qDebug()<<data.remove(2, 1); //10
Try out:
qDebug()<<QString(data); //10
Try out:
qDebug()<<data.replace('\x00', ""); //10
Try out:
Used Loop to go byte by byte, but same result
I want resulted string as a single string or split, no matter. But need full string something like 10;1395994881;1.0.0
or 10
and ;1395994881;1.0.0
.
I have also referred below Stack Overflow
questions.
1. QByteArray to QString
2. Remove null from string:Java
3. Code Project
EDIT
//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; //10\x00;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);
}
}
}
Please help me on this.
The QByteArray
returned by the serial port is created from raw data and does not behave like a character string. In order to process the full array you can use the STL style iterator which is robust to the included NULL
characters. For more info about fromRawData
arrays, please carefuly read the detailed description in the documentation.
Here's a dirty example showing how you can fix your string:
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; // "10\x00;1395994881;1.0.0"
char fixed[255];
int index = 0;
QByteArray::iterator iter = data.begin();
while(iter != data.end())
{
QChar c = *iter;
if (c != '\0') fixed[index++] = c.toLatin1();
iter++;
}
fixed[index] = '\0';
qDebug() << fixed; // 10;1395994881;1.0.0