Converting struct to byte and back to struct

前端 未结 4 1515
刺人心
刺人心 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:43

    You do things in the wrong order, the expression

    &struct_data+i
    

    takes the address of struct_data and increases it by i times the size of the structure.

    Try this instead:

    *((char *) &struct_data + i)
    

    This converts the address of struct_data to a char * and then adds the index, and then uses the dereference operator (unary *) to get the "char" at that address.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-31 04:47
    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; 
    }
    
    0 讨论(0)
  • 2021-01-31 04:52

    Always utilize data structures to its fullest..

    union AMG_ANGLES {
      struct {
        float yaw;
        float pitch;
        float roll;
      }data;
      char  size8[3*8];
      int   size32[3*4];
      float size64[3*1];
    };
    
    0 讨论(0)
提交回复
热议问题