文章目录
QBytearray
问题一:QByteArray数据在定义时会被\x00
打断。
代码段:
QByteArray ba = "\xFE\xEF\x03\x00\x11\x22\x33";
qDebug() << "ba.size = " << ba.size();
qDebug() << "ba = " << ba;
输出结果:
ba.size = 3
ba = "\xFE\xEF\x03"
原因:\x00
<=>'\0'
相当于字符串的结束符,字符串在遇到‘\0’时会被截断。
正确处理方式:
//方法一:
QByteArray ba = QByteArray::fromRawData("\xFE\xEF\x03\x00\x11\x22\x33", 7);
qDebug() << "ba.size = " << ba.size();
qDebug() << "ba = " << ba;
//方法二:
QString str = "FE EF 03 00 11 22 33";
QByteArray ba1 = QByteArray::fromHex(str.toLatin1().data());
qDebug() << "ba1.size = " << ba1.size();
qDebug() << "ba1 = " << ba1;
ba.size = 7
ba = "\xFE\xEF\x03\x00\x11\"3"
ba1.size = 7
ba1 = "\xFE\xEF\x03\x00\x11\"3"
问题二:toInt
,toShort
等用法
参考链接:https://www.cnblogs.com/xingzhensun/p/14046244.html
QByteArray中自带的数值转换方法是针对于ASCII码数值的转换,比如"15.225","65"
等。如果其中存储的是二进制数据则无法转换
// 测试一:ASCII转换为浮点数
QByteArray ba = "34.55";
float ba_to_float = ba.toFloat();
qDebug() << ba << "ba.toFloat() = " << ba_to_float;
// 测试二:二进制数据转换为uint16_t数据
QByteArray ba1 = "\x02\x03";
uint16_t ba_to_ushort = ba1.toUShort();
qDebug() << ba1 << "ba1.toUshort() = " << ba_to_ushort;
结果:
"34.55" ba.toFloat() = 34.55
"\x02\x03" ba1.toUshort() = 0 # 0表示转换失败
问题三:QByteArray数据和int、float等数据进行转换
参考链接:https://cloud.tencent.com/developer/article/1596356
通过memcpy
函数来实现
QByteArray数据转换为int类型数据:
QByteArray ba = QByteArray::fromRawData("\x44\x33\x22\x11",4);
int32_t aa;
memcpy(&aa, ba.data(), sizeof(aa));
qDebug() << "aa = " << QString::asprintf("%#x", aa);
结果:
aa = "0x11223344"
int数据转换为QByteArray类型数据:
int num = 0x02020202;
QByteArray ba,ba1;
//方式一:
ba.resize(4);
memcpy(ba.data(), &num, 4);
qDebug() << "ba = " << ba;
//方式二:
ba1.append((char *)&num, 4);
qDebug() << "ba1 = " << ba1;
结果:
ba = "\x02\x02\x02\x02"
ba1 = "\x02\x02\x02\x02"