Converting struct to byte and back to struct

前端 未结 4 1606
刺人心
刺人心 2021-01-31 04:21

I\'m currently working with Arduino Unos, 9DOFs, and XBees, and I was trying to create a struct that could be sent over serial, byte by byte, and then re-constructed into a stru

4条回答
  •  忘掉有多难
    2021-01-31 04:46

    It seems I've solved my issue with the following code.

    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
    }
    

    WARNING: This code will only work if sending and receiving are using the same endian architecture.

提交回复
热议问题