Search code examples
c++qtqstringqbytearray

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;
}

Solution

  • 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.