Search code examples
c++qtqbytearray

Passing QByteArray containing binary data to function by value


So I'm working on a large program that manipulates binary data stored in QByteArrays. Today, I realized that when I pass a QByteArray to a function by value, e.g.

void myFunc(QByteArray data)
{
 // Do stuff
}

that if my QByteArray has a 0x0 somewhere in the middle of the binary stream, like 0xA5 0x20 0x04 0x00 0x52. The 0x52 gets chopped off when the QByteArray is passed into the function.

I imagine that I could simply pass the QByteArray by value into the function, but there are some cases where I need a copy of the array (for data persistence or adding to a queue, etc) and unfortunately, I have many, many lines of code where such functions are passing around copied QByteArrays.

So I'm wondering if there is any way to overload the assignment operator (or use some other method) to copy the data between two QByteArrays without treating the 0x00 items as null-terminated string characters. I'm trying to find the simplest approach to this problem without having to completely gut my program and redo all the functions. Is there a better alternative datatype I can use (where i can just do a quick Find/replace, or some function I can wrap them in?

UPDATE: Added stripped down example to demo problem

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QByteArray data = QByteArrayLiteral("\xA5\x20\x04\x00\x52");

    doStuff(data);

    return a.exec();
}

void doStuff(QByteArray theData)
{
    // theData will contain only 0xA5 0x20 0x04 0x00 if you look from in here
}

UPDATE 2:

OK, apparently, after testing the above example. it actually DOES work. However, the real scenario I'm working with in a thread and I need to test more. Will update once I narrow the problem down more...


Solution

  • I dont think it has anything todo with passing the QByteArray by value but more like how you initialize your arrays. Consider this example:

    QByteArray data("\xA5\x20\x04\x00\x52");
    
    qDebug( data.toHex() );
    
    QByteArray data2;
    data2.append( static_cast<char>( 0xA5 ) );
    data2.append( static_cast<char>( 0x20 ) );
    data2.append( static_cast<char>( 0x04 ) );
    data2.append( static_cast<char>( 0x00 ) );
    data2.append( static_cast<char>( 0x52 ) );
    
    qDebug( data2.toHex() );
    

    The output is:

    a52004
    a520040052
    

    Initializing it with a string it chops of at the 0-termination. This also holds true for QByteArray::toStdString().

    EDIT:

    As Frank pointed out:

    QByteArray data("\xA5\x20\x04\x00\x52", 5);
    
    qDebug( data.toHex() );
    

    will indeed put out what is expected:

    a520040052