如何最有效地拆分QbyteArray? [英] How to split QbyteArray most efficiently?

查看:1138
本文介绍了如何最有效地拆分QbyteArray?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有效地对QByteArray消息进行分区,在1个字节后插入间隙。

QByteArray包含8byte数据。

I want to partition a QByteArray message efficiently, insert gap after 1 byte.
QByteArray contain 8byte data.

EX:
QByteArray qba = AABBCCDDEEFF9988



我想把它写入下面的txt文件中格式。


I want to write this into txt file in the following format.

AA BB CC DD EE FF 99 88





任何帮助都会很棒=)



Any help would be great =)

推荐答案

最好使用 printf 格式化:

This can be best done using printf formatting:
FILE *f = fopen("test.txt", "w");
for (int i = 0; i < qba.size(); i++)
{
    if (i)
        fprintf(f, " ");
    fprintf(f, "%02X", (unsigned char)qba.at(i));
}
fprintf(f, "\n");
fclose(f);



如果您的文件已经通过 fopen 之外的其他方法打开,请检查如果您可以获得打开文件的 FILE 指针,或者使用本地缓冲区使用 sprintf 并将其写入文件。



[更新]

对于现有的 QTextStream 喜欢评论吧可以是:


If your file is already opened by another method than fopen, check if you can get a FILE pointer for the opened file or use sprintf with a local buffer and write that to the file.

[UPDATE]
For an existing QTextStream like from the comment it can be:

mylog << " " << currtTimeStump "," << MsgDLC << "," << frameID << ",";
for (int i = 0; i < qba.size(); i++)
{
    char dataByte[4];
    sprintf(dataByte, " %02X", (unsigned char)qba.at(i));
    mylog << dataByte; 
}
mylog << '\n';


要将char(即byte)作为大写十六进制字符串写入输出流,您可以执行以下操作:
To write a char (i.e. a "byte") as upper case hex string into an output stream, you might do the following:
#include <iostream>
#include <iomanip>
...
ostream& toHex(ostream& output, unsigned char byte) {
    return output << hex
                  << uppercase
                  << setw(2)
                  << setfill('0')
                  << int(byte);
}

用法:

for(int i = 0; i < n; i++) {
    cout << toHex(cout, bytes[i]) << " ";
}
cout << endl;

干杯

Andi

Cheers
Andi


这篇关于如何最有效地拆分QbyteArray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆