Base 128 Varints

To understand your simple protocol buffer encoding, you first need to understand varints. Varints are a method of serializing integers using one or more bytes. Smaller numbers take a smaller number of bytes.

Each byte in a varint, except the last byte, has the most significant bit (msb) set – this indicates that there are further bytes to come. The lower 7 bits of each byte are used to store the two's complement representation of the number in groups of 7 bits, least significant group first.

So, for example, here is the number 1 – it's a single byte, so the msb is not set:

0000 0001
 

 

And here is 300 – this is a bit more complicated:

1010 1100 0000 0010
 

 

 

淺談 Base 128 varints 由來 : 

首先,我們要先了解Varints的意思,Varints是指使用一個或多個字節表示整型數據的方法,而除了最後一個字節之外的每個字節都包含一個msb ( most significant bit )設置(使用最高位),這就代表其後的字節是否和當前字節一起表示同型數值,而字節的其餘七位將用於儲存資料本身,然而,每個字節為8位,也就是Base 256,但是在Protocol buffer的編碼中,最高位成了msb,因此只有後面7位儲存實際的數據,所以才稱為 Base 128 ( 2的七次方 )。

 

而以下要教學的部分,

是這個300是如何來的。

 

 

300
=>1010 1100 0000 0010

將這邊拆成兩個字節
A = 1010 1100
B = 0000 0010


A的msb為1,說明後面的字節將連同該字節表是同一個數值

B的msb為0,代表他是最後一個字節了

然後去掉A和B的msb,這時 
A = 010 1100
B = 000 0010

而由於protocol buf是照little endian的方式,所以你要將兩個數值翻轉

A(010 1100) B(000 0010)
-> B( 000 0010 ) A(010 1100)

= 000 0010 010 1100


然後將翻轉後的兩個字節直接連接起來,並且去除高位數的0
= 100 101 100
接下來就轉成10進制
256+32+8+4 = 300

 

而這就是300的由來。

 

 

 

接下來,我們寫點Code吧 

#include <iostream>
using namespace std;
 
int main()
{
    int num = 44034;    //1010 1100 0000 0010
    int left = num >> 8;
    int right = num & 0xFF;
    //去掉首位
    left = left & 127;
    right = right & 127;

    //交換位置
    int newleft = right;
    int newright = left;

    //組合成一個數字
    newleft = newleft << 7;
    int value = newleft + newright;
    
    cout << value << endl;
    //Output: 300
}

 

其實這個小程式,就是把上面那些話變成程式碼而已,

並不會很難,所以~還不會的,在重新看一次吧 ! 

 

 

 

arrow
arrow

    Eric 發表在 痞客邦 留言(0) 人氣()