【QT】 负数 相互转换 16进制数组、字符串等
负数转16进制字符串
int result = -10000;
// 转为大写的十六进制
QString hexValue = QString::number(result, 16).toUpper();
qDebug() << "\r\n16进制数据: " << hexValue;
qDebug() << "16进制数据取最后8个字节 right(8): " << hexValue.right(8);
结果:
16进制数据: “FFFFFFFFFFFFD8F0”
16进制数据取最后8个字节 right(8): “FFFFD8F0”
16进制字符串 转 字节数组
// hexStr = "FFFFD8F0"
QByteArray ba = QByteArray::fromHex(hexStr.toLatin1());
// 开辟空间
unsigned char *dataCh = (unsigned char *)malloc(ba.length() * sizeof(unsigned char));
// 数组赋值
for (int i = 0; i < ba.length(); i++)
{
dataCh[i] = static_cast<unsigned char>(ba.at(i));
}
// 打印
for (int i = 0; i < ba.length(); i++)
{
qDebug() << i+1 << " :" << QString::number(dataCh[i], 16);
}
结果:
1 : “ff”
2 : “ff”
3 : “d8”
4 : “f0”
16进制字符串 转 10进制负数
// hexStr = "FFFFD8F0"
qDebug() << "直接string toUint 转:" << int(hexStr.toUInt(nullptr, 16));
QByteArray hexBa = QByteArray::fromHex(hexStr.toLatin1());
qDebug() << "通过bytearray 转:"<< int(hexBa.toHex().toUInt(nullptr,16));
int test = 0;
// dataCh[4] = {0xFF, 0xFF, 0xD8, 0xF0};
test = (dataCh[0] << 24 ) | (dataCh[1] << 16 ) | (dataCh[2] << 8 ) | (dataCh[3]);
qDebug() << "通过移位转:" << test;
结果:
直接string toUint 转: -10000
通过bytearray 转: -10000
通过移位转: -10000