c++ - 如何将枚举类型的数据保存到文件?

标签 c++ qt enums

我有枚举类型的数据,例如:

typedef enum
{
    NULLTYPE = 0U,
    ParameterGetType = 1U,
    ParameterSetType = 2U,
    ParameterStatusType  = 3U,
    EventActionType  = 4U,
    CommandType  = 5U,
    CommandGetType  = 6U,
    CommandSetType  = 7U,
    EquipmentIDGetType   = 15U,
    EquipmentIDSetType   = 16U,
    EquipmentIDStatusType = 17U,
    EventReportGetType  = 18U,
    EventReportSetType  = 19U,
    EventReportStatusType = 20U,
    PeriodicReportType = 21U,
    PeriodicReportGetType  = 22U,
    PeriodicReportSetType  = 23U,
    PeriodicReportStatusType  = 24U,
    CommandResponseType  = 25U,
    CommandResponseGetType  = 26U,
    CommandResponseSetType  = 27U,
    CommandResponseStatusType  = 28U,
    CommandResponseDeletedType  = 29U

}MessageType;

我想使用 QByteArray 和 QFile::write(QByteArray) 将它保存到二进制文件中,
但是我不知道数据的长度,以及数据的字节值的‘分布’,
(如果数据为1,其他字节的值是否为零?)
我觉得不限于qt,如何将数据写入文件?

(对于短类型数据(MsgItem->PIN),我会这样做:)

QByteArray bytes;
bytes.append(((MsgItem->PIN)>>8) & 0xff);
bytes.append((MsgItem->PIN) & 0xff);
MsgFile->write(bytes);
MsgFile->flush();

最佳答案

将枚举值转换为固定大小的整数(使用 <cstdint> 和例如 uint16_t )并执行您需要的任何字节排序操作。

关于c++ - 如何将枚举类型的数据保存到文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13773922/

相关文章:

c++ - Qt Creator/QMake 链接库

c++ - 在 Windows 7 64 位中未接收到 WM_WTSSESSION_CHANGE

C++ Eclipse 说参数无效(类型不正确)

python - 如何通过区分类型来隔离枚举?

c# - 处理意外枚举值的首选方法是什么?

java - 语法错误,插入 "Identifier"以完成 Enum Constant Header

c++ - 如何声明 "static"类/枚举?

c++ - 隐藏 QGraphicsItem 超出边界的区域

c++ - QAbstractSocket 没有那个文件或目录

c++ - 内容动态变化的QScrollArea