简体   繁体   中英

Protobuf packed (de)serialization

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?

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, ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM