I am using QT4.8 and I need to send an array to another device which includes some 0x00
values. However, QByteArray treats 0x00
value as of the end of the string. I wonder if it is even possible, what I am trying to achieve. here is my test code:-
zeroissue::zeroissue(QWidget *parent, Qt::WFlags flags)
: QMainWindow(parent, flags)
{
ui.setupUi(this);
unsigned char zero = 0x00;
QByteArray test;
test.append("this is a test");
test.append(zero);
test.append("test complete");
qDebug() << "test = " << test;
}
Please suggest me a way to treat 0x00
as a character in QByteArray.
I wonder if it is even possible,
Yes, it is. From QByteArray's documentation:
QByteArray can be used to store both raw bytes (including '\0's) and traditional 8-bit '\0'-terminated strings.
The following main
funtion works as expected
int main(int argc, char** argv)
{
char null_char = '\0';
QByteArray test;
test.append("this is a test");
std::cout << "size(): " << test.size() << std::endl;
test.append(null_char);
std::cout << "size(): " << test.size() << std::endl;
test.append("test complete");
std::cout << "size(): " << test.size() << std::endl;
return 0;
}
and produces the following expected output:
size(): 14
size(): 15
size(): 28
When you use
qDebug() << "test = " << test;
you should see the embedded null character in the output. See https://doc.qt.io/qt-5/qdebug.html#operator-lt-lt-20 for additional details.