25

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

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

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.
}

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

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

我该如何解决这个问题?

4

4 回答 4

40

看来我已经用下面的代码解决了我的问题。

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
}

警告:此代码仅在发送和接收使用相同的字节序架构时才有效。

于 2012-12-08T08:56:52.963 回答
7

你做事的顺序不对,表达

&struct_data+i

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

试试这个:

*((char *) &struct_data + i)

这会将地址转换struct_data为 achar *然后添加索引,然后使用解引用运算符(一元*获取该地址处的“char”。

于 2012-12-08T08:48:49.937 回答
4

始终充分利用数据结构。

union AMG_ANGLES {
  struct {
    float yaw;
    float pitch;
    float roll;
  }data;
  char  size8[3*8];
  int   size32[3*4];
  float size64[3*1];
};
于 2016-05-09T20:01:47.383 回答
1
for(unsigned int i = 0; i<sizeof(struct_data); i++){
    // +i has to be outside of the parentheses in order to increment the address
    // by the size of a char. Otherwise you would increment by the size of
    // struct_data. You also have to dereference the whole thing, or you will
    // assign an address to data[i]
    data[i] = *((char*)(&struct_data) + i); 
}

AMG_ANGLES* tmp = (AMG_ANGLES*)data; //Re-Make the struct
//tmp is a pointer so you have to use -> which is shorthand for (*tmp).yaw
cout << tmp->yaw; 
}
于 2012-12-08T08:53:26.803 回答