简体   繁体   English

在c ++中快速将原始数据转换为十六进制字符串

[英]Quickly convert raw data to hex string in c++

I'm reading data from a file and trying to display the raw data as 2 digit hex strings. 我正在从文件中读取数据并尝试将原始数据显示为2位十六进制字符串。

I'm using the Qt framework, specifically the QTextEdit. 我正在使用Qt框架,特别是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: 1)读入数据:

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): 2)创建一个将使用的QString(因为QTextEdit需要一个QString):

QString s;

3) Loop through the array appending each successive character to the QString s. 3)循环遍历数组,将每个连续的字符附加到QString。

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 现在这个工作正常,除非它到达字符FF ,它显示为FFFFFFFFFFFFFFFF

So my main questions are: 所以我的主要问题是:

  1. Why do only the 'FF' characters appear as 'FFFFFFFFFFFFFFFF' instead? 为什么只有'FF'字符显示为'FFFFFFFFFFFFFFFF'?
  2. Is there a way to convert the char data to base 16 strings without using QString::number? 有没有办法将char数据转换为基本16字符串而不使用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. 我希望这个实现尽可能快,所以如果像sprintf这样的东西可以工作,请告诉我,因为我猜想QString :: number可能会更快。

QString can't be used for binary data. QString不能用于二进制数据。 You should use QByteArray instead. 你应该使用QByteArray It can be easily created from char* buffer and can be easily converted to hex string using toHex . 它可以很容易地从char* buffer创建,并且可以使用toHex轻松转换为十六进制字符串。

QByteArray array(memblock, size);
textEdit->setText(QString(array.toHex()));

QString::number doesn't have an overload that takes a char , so your input is being promoted to an int ; QString::number没有带char的重载,所以你的输入被提升为int ; consequently you're seeing the effects of sign extension. 因此你看到了符号扩展的影响。 You should be seeing similar behavior for any input greater than 0x7F . 您应该看到任何大于0x7F输入0x7F类似的行为。

Try casting the data prior to calling the function. 在调用函数之前尝试转换数据。

s.append(QString::number(static_cast<unsigned char>(memblock[i]), 16).toUpper());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM