我正在处理一个返回字节数组的串行设备。 在这个数组中,存储着无符号短整型和无符号字符型的值。 我有以下结构:
typedef struct {
unsigned short RPM; //0
unsigned short Intakepress; //1
unsigned short PressureV; //2
unsigned short ThrottleV; //3
unsigned short Primaryinp; //4
unsigned short Fuelc; //5
unsigned char Leadingign; //6
unsigned char Trailingign; //7
unsigned char Fueltemp; //8
unsigned char Moilp; //9
unsigned char Boosttp; //10
unsigned char Boostwg; //11
unsigned char Watertemp; //12
unsigned char Intaketemp; //13
unsigned char Knock; //14
unsigned char BatteryV; //15
unsigned short Speed; //16
unsigned short Iscvduty; //17
unsigned char O2volt; //18
unsigned char na1; //19
unsigned short Secinjpulse; //20
unsigned char na2; //21
} fc_adv_info_t;
如何将数组映射到这种结构最好?从串行设备接收到的数组顺序与结构相匹配。
QByteArray
的生命周期内保持不变,请使用好老式的memcpy
。否则请使用reinterpret_cast
(它将节省您的复制,但会将结构体的生命周期绑定到QByteArray
本身。阅读:容易自己给自己惹麻烦)。如果字节序不匹配,则需要通过qFromLittleEndian
或qFromBigEndian
手动转换每个字段(取决于内存格式)。 - peppe