Qt|大小端数据转换-CSDN博客
之前这篇文章大小端数据转换如果是小数就会有问题。
第一个方法:
template <typename T>
static QByteArray toData(const T &value, bool isLittle) {
QByteArray data;
for (int i = 0; i < sizeof(T); ++i) {
int bitOffset = (isLittle) ? i : sizeof(T) - i - 1;
data.append(value >> bitOffset * 8);
}
return data;
}
float直接报错
第二个方法:
template <typename T>
QByteArray toData(T value, bool isLittle) {
QByteArray data;
QDataStream stream(&data, QIODevice::WriteOnly);
if (isLittle)
stream.setByteOrder(QDataStream::LittleEndian);
else
stream.setByteOrder(QDataStream::BigEndian);
stream << value;
return data;
}
测试float类型转换:
float类型占四个字节,打印的结果占有8个字节,明显是错误的。
直接查看内存中f的值:
f(3.14)在内存中为“c3f54840”,所以可以直接取地址进行转换,废话少说直接上代码:
template <typename T>
bool fromData(const QByteArray &data, bool isLittle, T &value) {
unsigned char *dataPtr = (unsigned char *)data.data();
unsigned char *valuePtr = (unsigned char *)&value;
for (int i = 0; i < sizeof(T); ++i) {
if (isLittle)
valuePtr[i] = dataPtr[i] & 0xff;
else
valuePtr[i] = dataPtr[sizeof(T) - i - 1] & 0xff;
}
return true;
}
template <typename T>
QByteArray toData(const T &value, bool isLittle) {
QByteArray data;
unsigned char *valuePtr = (unsigned char *)&value;
for (int i = 0; i < sizeof(T); ++i) {
if (isLittle)
data.append(valuePtr[i]);
else
data.append(valuePtr[sizeof(T) - i - 1]);
}
return data;
}
测试:
int main(int argc, char *argv[]) {
QCoreApplication a(argc, argv);
float f = 3.14;
QByteArray data = toData(f, true);
qDebug() << data.toHex();
float f1 = 0;
fromData(data, true, f1);
qDebug() << f1;
return a.exec();
}
编译运行查看打印:
与内存中查看一致