I am building PB messages containing 4 int32 fields. I wanted to add two more boolean fields to this message. I noticed that the size increased by 4 bytes for 2 boolean fields. Do the booleans occupy as large as 2 bytes per field. Can’t they be stored in a more compact form ?
Share
Each field header takes 1 byte (for low field numbers; more for large field numbers), and each bool takes 1 byte. There is no sub-byte packing in protobuf; things are rounded up to the nearest byte.
1 option would be to store an unsigned integer map – I.e. Treat each bool as a power of two and add them up (bitwise). Then you need one byte header and one byte data, so 2 bytes for both. You will, however, have to pack/unpack the integer yourself. Assuming you have a low field number, up to 7 bools is then 1 byte data plus 1 byte header. Since “varint” uses base-128 encoding (the msb is continuation), an 8th bool (up to 14 bools) would take 2 bytes data plus 1 byte header.