Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quickly convert raw data to hex string in c++

Tags:

c++

char

qt

I'm reading data from a file and trying to display the raw data as 2 digit hex strings.

I'm using the Qt framework, specifically the QTextEdit.

I've tried a bunch of different approaches and have almost accomplished what I want it to do, however it has some unexpected errors I don't know anything about.

Currently this is my implementation:

1) Read in the data:

ifstream file (filePath, ios::in|ios::binary|ios::ate);
if (file.is_open())
{
    size = file.tellg();
    memblock = new char [size+1];
    file.seekg(0, ios::beg);
    file.read(memblock, size);
    file.close();
}

2) Create a single QString that will be used (because QTextEdit requires a QString):

QString s;

3) Loop through the array appending each successive character to the QString s.

int count = 0;
for(i=0;i<size;i++)
{
    count++;;
    s.append(QString::number(memblock[i], 16).toUpper());
    s.append("\t");
    if (count == 16)
    {
        s.append("\n");
        count -= 16;
    }
}

Now this works fine, except when it reaches a character FF, it appears as FFFFFFFFFFFFFFFF

So my main questions are:

  1. Why do only the 'FF' characters appear as 'FFFFFFFFFFFFFFFF' instead?
  2. Is there a way to convert the char data to base 16 strings without using QString::number?

I want this implementation to be as fast as possible, so if something like sprintf could work, please let me know, as I would guess that might be faster that QString::number.

like image 925
krb686 Avatar asked Jun 20 '13 17:06

krb686


2 Answers

QString can't be used for binary data. You should use QByteArray instead. It can be easily created from char* buffer and can be easily converted to hex string using toHex.

QByteArray array(memblock, size);
textEdit->setText(QString(array.toHex()));
like image 123
Pavel Strakhov Avatar answered Sep 30 '22 08:09

Pavel Strakhov


QString::number doesn't have an overload that takes a char, so your input is being promoted to an int; consequently you're seeing the effects of sign extension. You should be seeing similar behavior for any input greater than 0x7F.

Try casting the data prior to calling the function.

s.append(QString::number(static_cast<unsigned char>(memblock[i]), 16).toUpper());
like image 23
Praetorian Avatar answered Sep 30 '22 06:09

Praetorian