black
black

Reputation: 357

Swapping bytes in a QByteArray

I want to write a simple function to swap bytes in a QByteArray. This is what I have come up with:

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

    QString t = "abcde";
    QByteArray test;
    test.append(t.at(0));
    test.append(t.at(1));
    test.append(t.at(2));
    test.append(t.at(3));
    test.append(t.at(4));

    qDebug() <<  t;
    qDebug() << QString(swapBytes(test,0,3));

    return a.exec();
}

QByteArray swapBytes(QByteArray in, int swapOffset, int quantity) {
    if (swapOffset < 0) {
        return in;
    }
    if(quantity>(in.length()/2)) {quantity=in.length()/2;}
    if(quantity < 1) {quantity=1;}
    int k;
    char buf[quantity];
    char buf2[quantity];
    qDebug() << quantity;
    for (int i = 0; i + quantity*2 + swapOffset <= in.length(); i=i+2*quantity) {
        k=i;
        for(int b = 0;b<i+quantity;b++){
            buf[b]=in.at(k);
            buf2[b]=in.at(k+swapOffset+quantity);
            k++;
        }
        qDebug() << buf;
        qDebug() << buf2;
        qDebug() << in;
        in.replace(0,quantity,buf2);
        qDebug() << in;
        in.replace(quantity+swapOffset,quantity,buf);
    }
    return in;
}

For some reason when I run this code I get the following output :

abcde
ab(
cd
abcde
cdcde
cdab(e

Where does the parentheses come from? As far as I know there is only one char per byte, so what is wrong?

Upvotes: 0

Views: 2636

Answers (1)

RA.
RA.

Reputation: 7777

You need to allocate one byte more than quantity to leave room for the null terminator. Try this:

char* buf = new char[quantity+1];
char* buf2 = new char[quantity+1];
memset(buf, 0, quantity+1);
memset(buf2, 0, quantity+2);

Then before your function returns, remember to deallocate:

delete [] buf;
delete [] buf2;
return in;

Alternately, you can just use a QByteArray in place of a char array:

QByteArray buf(quantity, 0x00);
QByteArray buf2(quantity, 0x00);

This allows you to skip calls to memset and to avoid worrying about deallocation.

Unrelated to all of this, note that you can initialize a QByteArray from a QString like this:

QByteArray test = t.toAscii();

Upvotes: 2

Related Questions