1. 程式人生 > >protobuf編碼格式

protobuf編碼格式

protobuf序列化出來的二進位制訊息特別的緊湊,得益於使用巧妙的編碼格式。

1、Varint

Varint 是一種緊湊的表示數字的方法。它用一個或多個位元組來表示一個數字,值越小的數字使用越少的位元組數。Varint 中的每個 byte 的最高位 bit 有特殊的含義,如果該位為 1,表示後續的 byte 也是該數字的一部分,如果該位為 0,則結束。其他的 7 個 bit 都用來表示數字。 因此小於 128 的數字都可以用一個 byte 表示。大於 128 的數字,比如 300,會用兩個位元組來表示:1010 1100 0000 0010

2、Key_Value

Google Protocol Buffer 位元組序採用 little-endian 的方式,訊息經過序列化後會成為一個二進位制資料流,該流中的資料為一系列的 Key-Value 對,每個欄位由欄位頭(key)和欄位體(value)組

Key 的定義如下: (field_number << 3) | wire_type

  • 第一部分是 field_number,表示欄位序號
  • 第二部分為 wire_type。表示 Value 的傳輸型別
    Wire Type
    Type Meaning  Used For
    0 Varint  int32, int64, uint32, uint64, sint32, sint64, bool, enum
    1 64-bit fixed64, sfixed64, double
    2 Length-delimi string, bytes, embedded messages, packed repeated fields
    3 Start group Groups (deprecated)
    4 End group Groups (deprecated)
    5 32-bit fixed32, sfixed32, float

3、zigzag編碼

sint32採用zigzag編碼

zigzag編碼:採用無符號數來表示有符號數字,正數和負數交錯

4、例子

300 時編碼如下 08 ac 02                       -- 記憶體中資料 08: 1 << 3 | 0 ac 02                            -- 轉換成二進位制 1010 1100 0000 0010 010 1100 0000 0010 1 0010 1100 300