Serialization/Deserialization of a struct to a char* in C

前端 未结 7 2029
清歌不尽
清歌不尽 2020-12-05 06:21

I have a struct

struct Packet {
    int senderId;
    int sequenceNumber;
    char data[MaxDataSize];

    char* Serialize() {
        char *message = new ch         


        
7条回答
  •  暖寄归人
    2020-12-05 06:30

    As mentioned in other posts, senderId and sequenceNumber are both of type int, which is likely to be larger than char, so these values will be truncated.

    If that's acceptable, then the code is OK. If not, then you need to split them into their constituent bytes. Given that the protocol you are using will specifiy the byte order of multi-byte fields, the most portable, and least ambiguous, way of doing this is through shifting.

    For example, let's say that senderId and sequenceNumber are both 2 bytes long, and the protocol requires that the higher byte goes first:

    char* Serialize() {
        char *message = new char[MaxMailSize];
    
        message[0] = senderId >> 8;
        message[1] = senderId;
    
        message[2] = sequenceNumber >> 8;
        message[3] = sequenceNumber;
    
        memcpy(&message[4], data, MaxDataSize);
    
        return message;
    }
    

    I'd also recommend replacing the for loop with memcpy (if available), as it's unlikely to be less efficient, and it makes the code shorter.

    Finally, this all assumes that char is one byte long. If it isn't, then all the data will need to be masked, e.g.:

        message[0] = (senderId >> 8) & 0xFF;
    

提交回复
热议问题