Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clean up QByteArray from \0

Tags:

arrays

string

qt

In my app I use QByteArray to read binary data from file to a byte record with fixed size. Actually all these records are strings. If the string size less then record size so the rest of bytes are filled with \0. Sometimes the record can start with \0 too.

Example, what I need to do:

Before

\0 \0 \0 T h e \32 s t r i n g \0 \0 \0

After

T h e \32 s t r i n g

So my question - how can I clean up QByteArray from all of \0?

like image 876
folibis Avatar asked Dec 31 '25 08:12

folibis


1 Answers

I tested this code and it's seems to work thanks to the QByteArray & QByteArray::replace(...) function.

QByteArray array;
array[0] = '\0';
array[1] = 'a';
array[2] = '\0';
array[3] = 'b';
array[4] = '\0';

qDebug() << "string:" << QString(array.toHex());
array.replace('\0',"");

qDebug() << "string:" << QString(array.toHex());

output:

string: "0061006200" 
string: "6162" 
like image 135
Martin Avatar answered Jan 01 '26 20:01

Martin