【问题标题】:split string into struct without knowing structure在不知道结构的情况下将字符串拆分为结构
【发布时间】:2021-07-23 15:15:21
【问题描述】:

我有 8 个字节的带有标志的字符串,其中一些是布尔值,一些是字符。我想要的是通过代码中的名称访问该标志,例如myStruct.value1

我根据自己的意愿创建了一些结构。我希望我可以将字符串拆分为该结构,因为两者的总大小均为 64 位。

// destination
typedef struct myStruct_t {
  uint8_t  value1  : 8;
  uint8_t  value2  : 8;
  uint16_t value3  : 16;
  uint8_t  value4  : 8;
  uint8_t  value5  : 1;
  uint8_t  value6  : 1;
  uint8_t  value7  : 1;
  uint8_t  value8  : 1;
  uint8_t  value9  : 1;
  uint16_t value10 : 11;
  uint8_t  value11 : 8;
} myStruct_t;

// source
char buf[8] = "12345678";

// read about strcpy and memcpy but doesn't work
memcpy(myStruct, buf, 8);

但是它不起作用,我收到以下错误消息:

error: cannot convert 'myStruct_t' to 'void*' for argument '1' to 'void* memcpy(void*, const void*, size_t)'
     memcpy(myStruct, buf, 8);
                            ^

【问题讨论】:

  • C++ 不是 C。您的代码表明您可能正在自学 C。
  • myStruct = buf 将失败,因为 myStruct 没有定义。假设 myStruct_t myStruct 被声明,buf 仍然有一个冲突的类型。代码看起来像 C,但被标记为 C++。因此,char buf[8] 需要一个额外的空间,即 9。

标签: c++ casting bit-fields


【解决方案1】:

memcpy 期望它的前两个参数是指针。

buf 这样的数组将隐式衰减为指针,但您的类型 myStruct_t 不会。

myStruct_t myStruct;
memcpy(&myStruct, buf, 8);
//     ^ produces a POINTER to myStruct

【讨论】:

    【解决方案2】:

    如果我正确理解您要执行的操作,我将首先将 8 个字符的缓冲区转换为二进制。然后,您可以从中提取子字符串,以获得所需的每个值的长度。最后,您可以将二进制字符串转换为它们的数值。

    另外,你应该让你的 char 数组大小为 9。你需要一个额外的字符作为空终止符。你目前拥有它的方式不会编译。

    【讨论】:

    • 您能详细说明一下吗? value3 有问题(猜测与compiler padding 有关)memcpy 并不总是映射正确
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多