Home > Net >  Converting QByteArray to hex, bin and char
Converting QByteArray to hex, bin and char

Time:12-17

I have been trying to convert QByteArray data into a hex, bin and char tabular representation, but I encounter problems when in the QByteArray there are escape sequences... for example if I have the QByTeArray which contains "Hello World" the space is not converted into Hex, but it remains a space... what do I do?

 for (int i = 0; i < n; i  ){

         std::cout << "0x" << QString::number(0, 16).toStdString() << "\t";

         if (((i 1) % 8) == 0)
             std::cout << std::endl;
    }

this is the code used for example to run through the QByteArray and transform it into a hex representation.

Btw, I am using QT creator to program in C and I'm a beginner

I tried converting the QByteArray into a QString containing the translation into ASCII of the data, so that then maybe with an if else explain the behaviour the program should have every it encounters a number from 00 to 32... but it requires massive effort. Isn't there a shortcut?

CodePudding user response:

In your example, you never use a QByteArray but instead output 0x0 for n iterations.

Assuming, you have some array containing "Hello World", your loop correctly outputs hex values iff you use i to access the array elements and .length() instead of n:

const QByteArray data = "Hello World";
for (int i = 0; i < data.length(); i  ){
    
    std::cout << "0x" << QString::number(data[i], 16).toStdString() << "\t";
    
    if (((i 1) % 8) == 0)
        std::cout << std::endl;
}

Output:

0x48    0x65    0x6c    0x6c    0x6f    0x20    0x57    0x6f    
0x72    0x6c    0x64    
  • Related