【问题标题】:Serialize python class to C-type struct (with bit-padding) for sending over socket将 python 类序列化为 C 类型结构(带位填充)以通过套接字发送
【发布时间】:2018-05-09 07:35:36
【问题描述】:

我有一个接受传入数据包的服务器,如下 C++ 结构:

struct data_point
{
    uint32_t    type           : 8;
    uint32_t    id             : 24;
    uint32_t    timestamp_sec;
    uint32_t    timestamp_msec : 10;
    uint32_t    status         : 4;
    uint32_t    value          : 18;
};

我制作了一个基于 python 的客户端,它具有以下 DataPoint 类:

class DataPoint :
    def __init__(self, type, id, sec, msec, status, value) :
        self._type = type
        self._id = id
        self._sec = sec
        self._msec = msec
        self._status = status
        self._value = value

如何将DataPoint 序列化为二进制格式并通过套接字发送以供服务器正确接受?

【问题讨论】:

  • 为什么不用json?
  • @yumetodo 用于减少流量 该结构经过严格设计,但我没有做到。

标签: c++ python-2.7 sockets serialization


【解决方案1】:

使用struct.unpack()
https://docs.python.org/2.7/library/struct.html#module-struct

而且你还需要手动编写二进制操作...

【讨论】:

    猜你喜欢
    • 2016-04-04
    • 2011-06-18
    • 2016-10-12
    • 1970-01-01
    • 2016-06-06
    • 2011-10-07
    • 1970-01-01
    • 2011-08-05
    • 1970-01-01
    相关资源
    最近更新 更多