如何将QBytearrayBCD转换为十进制QString表示

How To Convert QBytearray BCD to Decimal QString Representation?

本文关键字:十进制 QString 表示 转换 QBytearrayBCD      更新时间:2023-10-16

嗨,我从一个文件中读取了一个压缩BCD,我想将其转换为十进制表示。数据长度为32字节,例如,这就是文件中的内容:

95 32 07 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 01 00 13 00

我想按原样显示数据,我该怎么做?

谢谢schef,它对我有用。我还有一个问题:我读到的一些数据是原始十六进制格式的数字数据,例如:

22 d8 ce 2d

必须解释为:

584633901

什么是最好、最快的方法?目前我是这样做的:

QByteArray DTByteArray("x22 xd8 xce x2d");
QDataStream dstream(DTByteArray);
dstream.setByteOrder(QDataStream::BigEndian);
qint32 number;
dstream>>number;

对于1和2字节整数,我这样做:

QString::number(ain.toHex(0).toUInt(Q_NULLPTR,16));

我开始研究QByteArray是否已经有合适的东西可用,但我找不到任何东西。因此,我只是写了一个循环。

testQBCD.cc:

#include <QtWidgets>
int main()
{
QByteArray qBCD(
"x95x32x07x00x00x00x00x00x00x00x00x00x00x00x00x00"
"x00x00x00x00x00x00x00x00x00x00x00x00x01x00x13x00",
32);
QString text; const char *sep = "";
for (unsigned char byte : qBCD) {
text += sep;
if (byte >= 10) text += '0' + (byte >> 4);
text += '0' + (byte & 0xf);
sep = " ";
}
qDebug() << "text:" << text;
return 0;
}

testQBCD.pro:

SOURCES = testQBCD.cc
QT += widgets

编译和测试(cygwin64,Window 10 64位(:

$ qmake-qt5 
$ make
g++ -c -fno-keep-inline-dllexport -D_GNU_SOURCE -pipe -O2 -Wall -W -D_REENTRANT -DQT_NO_DEBUG -DQT_WIDGETS_LIB -DQT_GUI_LIB -DQT_CORE_LIB -I. -isystem /usr/include/qt5 -isystem /usr/include/qt5/QtWidgets -isystem /usr/include/qt5/QtGui -isystem /usr/include/qt5/QtCore -I. -I/usr/lib/qt5/mkspecs/cygwin-g++ -o testQBCD.o testQBCD.cc
g++  -o testQBCD.exe testQBCD.o   -lQt5Widgets -lQt5Gui -lQt5Core -lGL -lpthread 
$ ./testQBCD 
text: "95 32 7 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 13 0"
$

我希望我正确解释了术语"打包BCD"。我相信我做到了(至少根据维基百科二进制编码的十进制–压缩BCD(。如果符号的支持成为一个问题,这将意味着一些额外的麻烦。