如果您只需要将 double 编码和解码为字节数组,则可以使用:
double value = 3.14159275;
// Encode the value into the byte array
QByteArray byteArray(reinterpret_cast<const char*>(&value), sizeof(double));
// Decode the value
double outValue;
// Copy the data from the byte array into the double
memcpy(&outValue, byteArray.data(), sizeof(double));
printf("%f", outValue);
然而,这并不是通过网络发送数据的最佳方式,因为这将取决于机器如何编码双精度类型的平台细节。我建议您查看QDataStream类,它允许您这样做:
double value = 3.14159275;
// Encode the value into the byte array
QByteArray byteArray;
QDataStream stream(&byteArray, QIODevice::WriteOnly);
stream << value;
// Decode the value
double outValue;
QDataStream readStream(&byteArray, QIODevice::ReadOnly);
readStream >> outValue;
printf("%f", outValue);
现在这是独立于平台的,流操作符使它非常方便和易于阅读。