将struct转换为byte并返回struct

Ste*_*172 21 c++ byte struct arduino xbee

我目前正在使用Arduino Uno,9DOF和XBee,我正在尝试创建一个结构,可以通过串行,逐字节发送,然后重新构造成结构.

到目前为止,我有以下代码:

struct AMG_ANGLES {
    float yaw;
    float pitch;
    float roll;
};

int main() {
    AMG_ANGLES struct_data;

    struct_data.yaw = 87.96;
    struct_data.pitch = -114.58;
    struct_data.roll = 100.50;

    char* data = new char[sizeof(struct_data)];

    for(unsigned int i = 0; i<sizeof(struct_data); i++){
        // cout << (char*)(&struct_data+i) << endl;
        data[i] = (char*)(&struct_data+i); //Store the bytes of the struct to an array.
    }

    AMG_ANGLES* tmp = (AMG_ANGLES*)data; //Re-make the struct
    cout << tmp.yaw; //Display the yaw to see if it's correct.
}
Run Code Online (Sandbox Code Playgroud)

资料来源:http://codepad.org/xMgxGY9Q

这段代码似乎不起作用,我不确定我做错了什么.

我该如何解决这个问题?

Ste*_*172 32

看来我用以下代码解决了我的问题.

struct AMG_ANGLES {
    float yaw;
    float pitch;
    float roll;
};

int main() {
    AMG_ANGLES struct_data;

    struct_data.yaw = 87.96;
    struct_data.pitch = -114.58;
    struct_data.roll = 100.50;

    //Sending Side
    char b[sizeof(struct_data)];
    memcpy(b, &struct_data, sizeof(struct_data));

    //Receiving Side
    AMG_ANGLES tmp; //Re-make the struct
    memcpy(&tmp, b, sizeof(tmp));
    cout << tmp.yaw; //Display the yaw to see if it's correct
}
Run Code Online (Sandbox Code Playgroud)

警告:此代码仅在发送和接收使用相同的endian体系结构时才有效.

  • 除了你的警告,双方也需要同样代表一个浮动.我建议将其作为定点整数发送(在上面的示例中:8796,-11458,10050)并记录值的字节顺序.使用`endian.h`中的`htobe32()`之类的函数在host和big-little-endian之间进行转换. (2认同)
  • @ Steven10172结构有没有填充?这不会紧紧包装结构. (2认同)

Som*_*ude 7

你以错误的顺序做事,表达式

&struct_data+i
Run Code Online (Sandbox Code Playgroud)

获取地址struct_data并将其增加到i 结构大小的倍数.

试试这个:

*((char *) &struct_data + i)
Run Code Online (Sandbox Code Playgroud)

这种转换的地址struct_datachar *添加索引,然后使用引用操作(一元*),以得到"字符"在该地址.


小智 5

始终充分利用数据结构..

union AMG_ANGLES {
  struct {
    float yaw;
    float pitch;
    float roll;
  }data;
  char  size8[3*8];
  int   size32[3*4];
  float size64[3*1];
};
Run Code Online (Sandbox Code Playgroud)