Home > Software engineering >  Protobuf packed (de)serialization
Protobuf packed (de)serialization

Time:08-05

Since protobuf does not support the uint16_t datatype, I have a field below describing what I have in place.

uint32_t fingerprints = 1 [packed=true];

To save space, I have a C program that packs together two uint16_t values and add them that way, here is an example:

uint16_t value1 = 100; // Arbitrary values
uint16_t value2 = 200;
protoObject.add_fingerprints((uint32_t)value1 << 16)    value2;

To deserialize them, I do:

uint16_t value1 = protoObject->fingerprints(i) >> 16;
uint16_t value2 = protoObject->fingerprints(i) & 0x0000FFFF;

However, it seems like this does not produce the values I want, and the values after deserialization does not match the values before it. Is there something special protobuf does that prevents me from doing this?

CodePudding user response:

To save space, I have a C program that packs together two uint16_t values and add them that way

No bother to do that. Protobuf uses variable length encoding to serialize uint32_t, which will do 'pack' for you to save space, i.e. for an uint16_t number, protobuf will not encode it to 4 bytes, instead, it might encode it to less than 2 bytes, depends on the number.

  • Related