开发者

Python equivalent of Perl's 'w' packing format

What format I should use in struct.unpack to decode data packed in perl us开发者_开发问答ing w format character (as doc says 'BER compressed integer')?


I don't believe python's struct module has support for that format, it mainly supports only the encodings that are commonly found in C structs. BER & DER encodings are generally only encountered within ASN.1 encoded streams... one of the Python ASN.1 modules might be helpful in that case (I should note they are not that user-friendly).

If not, you may have to implement a decoder yourself. The following bit of code will read off an int, and return where in the string that unpacking should pick up at...

def decode_ber_int(data, offset):
    value = 0
    while True:
        tmp = ord(data[offset])
        value = (value<<7) | (tmp&0x7f)
        offset += 1
        if tmp & 0x80 == 0:
            break
    return value, offset

Sadly, this will probably require breaking up your unpack call into unpack, decode_ber_int, and unpack the rest.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜