Protocol buffer 编码和解码 谷歌 整数变长编码

#include <iostream>
#include <unordered_map>
#include <string>
#include <cstring>
#include <iomanip>
using namespace std;

void encode(unsigned int n){
    if(n < 128) {
        if(n < 16) cout <<"0X0"<<hex<<n;
        else cout <<"0X"<<hex<<n;  
        return;
    }
    while(n){
        unsigned int tmp;
        if(n >= 128){
            tmp = (0x80 | (n & 0x7F));
            cout<<"0X"<<setiosflags(ios::uppercase)<<hex<<tmp;//大写16进制数字
        }else{
            tmp = (0x00|(n & 0x7F));
            if(tmp < 16) cout <<"0X0"<<hex<<tmp;
            else cout <<"0X"<<hex<<tmp;
        }
        n >>= 7;
    }
    return;
}
unsigned int decode(string& x){
    unsigned int u, res = 0;
    int cnt = 0;
    while(x.size()){
        string tmp = x.substr(0,4);
      //必须要依据格式输入 否则超索引范围
        x = x.substr(4);
        tmp = tmp.substr(2);
        u = 0;
        for(int i = 0; i < tmp.size(); i++){  
            if(tmp[i] >='0' && tmp[i] <= '9') u = u * 16 + tmp[i] - '0';
            if(tmp[i] >='A' && tmp[i] <= 'F') u = u * 16 + tmp[i] - 'A' + 10;
        }
        unsigned int temp;
        temp = (u & 0x7F);
        for(int i = 1; i <= cnt; i++){  
            temp <<= 7;
        }
        res += temp;
        cnt++;
    }
    return res;
}

int main(){ 
    unsigned int n;
    string x;
    cin >> n >> x;
    encode(n);
    cout <<endl;
    cout <<dec<<decode(x)<<endl; 
    return 0;
    /*
    999 - 0XE70X07
    100 - 0X64
    */
}



posted on 2020-08-05 21:54  BITChase  阅读(927)  评论(0编辑  收藏  举报

导航