Search code examples
c++structbytearduinoxbee

Converting struct to byte and back to struct


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

So far I have 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;

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

Source: http://codepad.org/xMgxGY9Q

This code doesn't seem to work, and I'm not sure what I'm doing wrong.

How do I solve this?


Solution

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