簡體   English   中英

將struct轉換為byte並返回struct

[英]Converting struct to byte and back to struct

我目前正在使用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.
}

資料來源: http//codepad.org/xMgxGY9Q

這段代碼似乎不起作用,我不確定我做錯了什么。

我該如何解決這個問題?

看來我用以下代碼解決了我的問題。

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
}

警告:此代碼僅在發送和接收使用相同的endian體系結構時才有效。

你以錯誤的順序做事,表達式

&struct_data+i

獲取struct_data的地址並將其增加i 倍於結構的大小

試試這個:

*((char *) &struct_data + i)

這會將struct_data的地址轉換為char *然后添加索引,然后使用解除引用運算符(一元* )來獲取該地址的“char”。

始終充分利用數據結構..

union AMG_ANGLES {
  struct {
    float yaw;
    float pitch;
    float roll;
  }data;
  char  size8[3*8];
  int   size32[3*4];
  float size64[3*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; 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM