Search code examples
c++qttype-conversionasciinon-ascii-characters

Handling ASCII characters in a char to QString conversion


I have a bit of trouble with converting a char to QString, as it keeps dumping ASCII characters instead of the sum I would like to be in its hex byte form (e.g. ffd0).


A bit of a walk through of the code I have - I have a string of hex values (A1-B2-C3), which is in a QByteArray and is operated on by a checkSum function I have created. The output is a checksum byte (ffd0) and it is printed properly on the terminal with printf("%x", checkSum(output)); but when I am using the ui functions of Qt, it prints out rubbish.

What is the most efficient way of doing this on the Qt Creator?


Here is some extra clarification:

Input:

A1-B2-C3

Output:

Label - "￐"(Nonsenical ascii and, sometimes, the ocasional katakana and hiragana, purely depending on the inputted hex)

printf - ffd0 (Which is the proper output and the one that I would like set as the text of the label and lineEdit)


Code Bit:

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

    return val;
}

...

 QChar resultCh =  checkSum(output);

        ui->lineEdit->setText(resultCh);
        ui->outputLabel->setText(resultCh);

        printf("%x\n", resultCh);
...

Solution

  • The correct result is not ffd0 but d0.

    Why copying char to QChar? If, for some reason, you still want to do this, you should convert it to its unicode value before using it:

    printf("%x", resultCh.unicode());
    

    and:

    ui->lineEdit->setText(QString("%1").arg(resultCh.unicode(), 0, 16));
    

    Note that printf("%x", resultCh); should give you a big warning while compiling.