Search code examples
c++qtqstringqtcoreqbytearray

Converting Character data to QString in Qt Creator


enter image description hereI'm working on a QT project (Qt Creator 5.2.1) with a function that receives a receives a device's IP address in a UDP datagram. I need to convert it to a QString to correctly output to the screen. The datagram is stored in a QByteArray called "buffer" as integer data - so the IP address of 10.1.10.60 shows up in the datagram as 0A010A3C. I'm trying to store the IP address in a QString "nburn_data". Currently I have this code for handling it:

nburn_data.append(QString::fromUtf8(buffer.left(2).toHex().toUpper(), 
    buffer.left(2).size()));

When the output is put to the screen (GUI) I don't get "10.1.10.60", I get "0A.01.0A.3C"

I've tried a few different methods to convert correctly, but nothing seems to be working. Any suggestions?

Edit: @Laszlo Papp- I've attached an image along with the output (highlighted) from suggested code. Relevant Code and Output


Solution

  • I do not understand what you try to do with your code as it seems to be out of order, but the following code works for me:

    main.cpp

    #include <QString>
    #include <QByteArray>
    #include <QDebug>
    
    int main()
    {
        QByteArray buffer = "0A010A3C";
        QString nburn_data;
        bool ok;
        for (int i = 0; i < 8; i+=2) {
            if (i)
                nburn_data.append('.');
            nburn_data.append(QByteArray::number(buffer.mid(i, 2).toInt(&ok, 16)));
            // when using int buffer, then replace the above line with this:
            // nburn_data.append(buffer.mid(i, 2));
        }
        qDebug() << nburn_data;
        return 0;
    }
    

    main.pro

    TEMPLATE = app
    TARGET = main
    QT = core
    SOURCES += main.cpp
    

    Build and Run

    qmake && make && ./main
    

    Output

    "10.1.10.60"
    

    Edit: since you seem to have changed your input when updating the question, you will need to this update to my previous code answering your original question:

    tempbuffer = tempbuffer.toHex(); // before the loop in your code
    

    or you could just remove the needless number conversion in my loop, so replacing the inner line with this:

    nburn_data.append(buffer.mid(i, 2));