Joe Carr
Joe Carr

Reputation: 455

Qt - QStringList to QByteArray

What is the most efficient way of converting QStringList to QByteArray?

I have found many examples of similar conversions but never the one I needed or were just needlessly too complicated.


The code sanitize a string input and then convert it to QByteArray. I am struggling with the latter part.

void MainWindow::on_suicideButton_clicked()
{
    QString input = ui->lineEdit->text();
    try{
        if(ui->lineEdit->text().contains("0x")||ui->lineEdit->text().contains(",")||ui->lineEdit->text().contains("-"))
        {
            input = input.replace("0x","");
            if (input.contains(',')) input = input.replace(",", "");
            // QString trim = input.trimmed();
            // input = trim;//.split(',', ' ', '-');
            QStringList inputArray = input.split('-');
            QByteArray output = inputArray;
        }
        //printf("%s\n", input);

        ui->lineEdit->setText(input);
    }
    catch (const std::bad_alloc &) {input = " ";}
}

QStringList inputArray = input.split('-'); is important (or at least I believe it to be so), as I would need to split the bytes into separate chunks in order to perform various operations on them.


Here is an example, in order for you to see what kind of operations I would like to do:

char MainWindow::checkSum(QByteArray &b)
{
    char val = 0x00;
    char i;
    foreach (i, b)
    {
       val ^= i;
    }

    return val;
}

Upvotes: 2

Views: 6731

Answers (4)

KelvinS
KelvinS

Reputation: 3061

As dydil also answered, you can use QDataStream.

For example:

QByteArray serialize(QStringList data)
{
    QByteArray byteArray;
    QDataStream out(&byteArray, QIODevice::WriteOnly);
    out << data;
    return byteArray;
}

void deserialize(QByteArray byteArray, QStringList *data)
{
    QDataStream in(&byteArray, QIODevice::ReadOnly);
    in >> *data;
}

Upvotes: 2

Elcan
Elcan

Reputation: 824

If I understand correctly, you will have to join the strings with a separator of your choice, then have to use one of the QString functions to convert to QByteArray depending on the QStrings encoding

QStringList strlist; //Let's assume there's a value in there

QChar separator = ''; //Any QChar or QString you want to use to separate the QStringList
strlist.join(separator).toLocal8Bit(); //8 bit
strlist.join(separator).toUtf8(); //UTF-8
strlist.join(separator).toLatin1(); //Latin

Edit 1 to fit your code

if(input.contains("0x")||input.contains(",")||input.contains("-"))
{
    //Just replace the chars you don't cant, then convert back to QByteArray
    input = input.replace("0x","");
    input = input.replace(",", "");
    input = input.replace("-", "");
    QByteArray output = input.toLocal8Bit();
}

Edit 2 with QStringList

if(input.contains("0x")||input.contains(",")||input.contains("-"))
{
    //Just replace the chars you don't cant, then convert back to QByteArray
    input = input.replace("0x","");
    input = input.replace(",", "");
    QStringList inputArray = input.Split('-');

    //Do what you want with your list
    //...

    //Converts it back
    QByteArray output = inputArray.join('').toLocal8Bit();
}

I cannot test the code right now, so there might be a typo

Upvotes: 2

dydil
dydil

Reputation: 997

How about a QDataStream to serialize the string list?

// Fill the data buffer
QByteArray data;
QStringList list{"foo", "bar", "foobar"};
QDataStream dataStreamWrite(&data, QIODevice::WriteOnly);
dataStreamWrite << list;

// Do whatever you want with the raw data

// And if you want to convert it back to a QStringList
QDataStream dataStreamRead(data);
QStringList list2;
dataStreamRead >> list2;

Upvotes: 5

Yuriy Ivaskevych
Yuriy Ivaskevych

Reputation: 966

You can simply apply QByteArray::append(const QString &str) for each string in your list. Docs says it will automatically convert string:

Appends the string str to this byte array. The Unicode data is converted into 8-bit characters using QString::toUtf8().

So you can write something like this:

QByteArray output;

// inputArray - your QStringList
foreach (const QString &str, inputArray)
{
    output.append(str);
}

But if you don't want default conversation you can append strings converted to const char * as stated in the same docs:

You can disable this function by defining QT_NO_CAST_TO_ASCII when you compile your applications. You then need to call QString::toUtf8() (or QString::toLatin1() or QString::toLocal8Bit()) explicitly if you want to convert the data to const char *.

And do something like this:

output.append(str.toUtf8()); // or str.toLatin1() or str.toLocal8Bit()

Edit 1

Just found that you can also use += instead of append() :

output += str;

This would behave the same way as append() as said here.

Upvotes: 2

Related Questions