3

我需要序列化要通过网络发送的枚举值。发送部分使用 C 语言并在 8 位微控制器上运行,没有可用的协议缓冲区或类似库。接收部分使用 C++ (Linux)。我尝试了以下方法:

enum enum_x {
    V1 = 1,
    V2 = 2,
};

enum enum_y {
    V3 = 1,
    V4 = 2,
    V5 = 3,
};

enum enum_z {
    V6 = 1,
    V7 = 2,
    V8 = 3,
};

uint8_t serialize_enums(enum_x x, enum_y y, enum_z z) {
    return x * 100 + y * 10 + z;
}

但这似乎无效。它在我的 Linux 机器上工作正常,但在 8 位系统上结果不正确(y 值似乎存储为 z 并且 z 值丢失)。我试图添加演员表:

return (uint8_t)x * 100 + (uint8_t)y * 10 + (uint8_t)z;

但它没有帮助。什么是正确的方法?

4

1 回答 1

0

If you want to send them in an 8-bit field, allow for values between 0-3 for each enum, I would do something like this:

#include <iostream>
#include <cstdint>

struct s_enum_t
{
   s_enum_t(
      int x,
      int y,
      int z)
      : x_(x)
      , y_(y)
      , z_(z)
   {}

   union
   {
      struct
      {
         uint8_t x_ : 2;
         uint8_t y_ : 2;
         uint8_t z_ : 2;
         uint8_t spare_ : 2;
      };
      uint8_t val;
   };
};

int main()
{
   s_enum_t v(1, 1, 1);

   std::cout << v.val << "\n";
}

That will get the values laid out in a very specific manner. When sending between different systems you have to be aware of the endian scheme for each system though.

To clarify, with each individual enumerated value laid out in 2-bits, it becomes easier to troubleshoot issues between the sending and receiving systems. In this particular case, you have to be familiar with how this will be laid out on each system (by the compiler) to know how to properly decode the values. Having individual values in a bitfield that can be printed out (for debugging purposes) allows you to easily identify which fields are which when doing the initial system integration testing.

于 2012-10-18T14:49:44.940 回答