Skip to content

Instantly share code, notes, and snippets.

@liyonghelpme
Created July 19, 2015 10:12
Show Gist options
  • Save liyonghelpme/d7d030f5c592333bb734 to your computer and use it in GitHub Desktop.
Save liyonghelpme/d7d030f5c592333bb734 to your computer and use it in GitHub Desktop.
decode protobuff wireformat
#coding:utf8
#解析protobuf wireformat
#https://developers.google.com/protocol-buffers/docs/encoding
import struct
f = open('server0_5.json').read()
#filenum << type value
#0 varint
# 1 fix64
# 2 length-delimited
# 5 fix32
#读取一个变长整数
#返回新的位置
def readVarint(stream, start):
result = 0
c = 0
while True:
byte = stream[start]
intv = struct.unpack('B', byte)[0]
print 'byte', hex(intv), intv, bin(intv)
more = intv& 0b10000000
v = intv & 0b01111111
result += v << c
print 'ret', result, v, c, bin(v), more
c += 7
if more == 0:
break
else:
start += 1
print result
start += 1
wireType = result & 0b111
fieldNum = result >> 3
print bin(fieldNum), bin(wireType)
print fieldNum, wireType
print start, result, fieldNum, wireType
return start, result, fieldNum, wireType
state = 0
readState = 0
i = 0
form = ''
while i < len(f):
if state == 0:
i, result, fieldNum, wireType = readVarint(f, i)
if wireType == 2:
i, length, _, _ = readVarint(f, i)
form += str(['fieldNum', fieldNum, 'wireType', wireType, 'length', length, 'value', f[i:i+length]])+'\n'
i += length
elif wireType == 0:
i, value, _, _ = readVarint(f, i)
form += str(['fieldNum', fieldNum, 'wireType', wireType, 'value', value])+'\n'
else:
print 'Error: UnSupport Type', wireType
readVarint(f, 0)
print form
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment