[英]Qt-how to convert a QByteArray to struct
I need to convert a QByteArray
to structure. 我需要将
QByteArray
转换为结构。 I have a structure like this: 我有这样的结构:
struct mavlink_attitude_t
{
/// <summary> Timestamp (milliseconds since system boot) </summary>
quint32 time_boot_ms;
/// <summary> Roll angle (rad, -pi..+pi) </summary>
float roll;
/// <summary> Pitch angle (rad, -pi..+pi) </summary>
float pitch;
/// <summary> Yaw angle (rad, -pi..+pi) </summary>
float yaw;
/// <summary> Roll angular speed (rad/s) </summary>
float rollspeed;
/// <summary> Pitch angular speed (rad/s) </summary>
float pitchspeed;
/// <summary> Yaw angular speed (rad/s) </summary>
float yawspeed;
};
and I have a QbyteArray
comes from the serial port. 我有一个
QbyteArray
来自串行端口。 I already used union but I think it can't be used for QByteArray
. 我已经使用过union,但是我认为它不能用于
QByteArray
。 Is there any other way? 还有其他办法吗? an example can really help.
一个例子真的有帮助。
You can cast it: 您可以投射它:
QByteArray arr;
mavlink_attitude_t* m = reinterpret_cast<mavlink_attitude_t*>(arr.data());
The accepted response could not work. 接受的响应无效。
.data()
is null terminated. .data()
以null终止。
You have floats and ints, use shift left. 您有浮点数和整数,请使用向左移动。
Example: 例:
mavlink_attitude_t.time_boot_ms = (bytearray.at(0) & 0xFFFF) |
(bytearray.at(1) & 0xFFFF) << 8 |
(bytearray.at(2) & 0xFFFF) << 16|
(bytearray.at(3) & 0xFFFF) << 24
if you use Little endian, inverse the indexs. 如果使用Little endian,则反索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.