javageometryprotocol-buffersprotobuf-java

In Protobuf, are double or float types fixed size when serialized?


Are 'double' and 'float' data types fixed size in Protobuf? Do they occupy a fixed number of bytes (say 8 or 4 bytes) when serialized no matter what value (big or small) they actually keep? I want to use one of them to keep latitude and longitude. If they're fixed, then I think it makes sense to use 'float' instead as it seems to be enough?


Solution

  • According to Google protobuf encoding docs, double will be fixed of 8-bytes, and float is fixed 4-bytes when serialized

    Non-varint numeric types are simple – double and fixed64 have wire type I64, which tells the parser to expect a fixed eight-byte lump of data. We can specify a double record by writing 5: 25.4, or a fixed64 record with 6: 200i64. In both cases, omitting an explicit wire type implies the I64 wire type.

    Similarly float and fixed32 have wire type I32, which tells it to expect four bytes instead. The syntax for these consists of adding an i32 prefix. 25.4i32 will emit four bytes, as will 200i32. Tag types are inferred as I32. float would depend on your specific needs for precision:

    When it comes to representing latitude and longitude, your choice between double and float would depend on your specific needs for precision:

    In summary, if you don't require extremely high precision, a float should be sufficient for storing latitude and longitude coordinates. Using float over double could also save some space, especially if you have a large dataset of such coordinates to store or transmit.

    I hope this helps clarify your question!