auto-repeat flag in a pack format string

后端 未结 2 1122
[愿得一人]
[愿得一人] 2020-12-21 03:57

In php, unpack() has the \"*\" flag which means \"repeat this format until the end of input\". For example, this prints 97, 98, 99

$str = \"abc\";
$b = unpac         


        
2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-21 04:41

    There is no such facility built into struct.unpack, but it is possible to define such a function:

    import struct
    
    def unpack(fmt, astr):
        """
        Return struct.unpack(fmt, astr) with the optional single * in fmt replaced with
        the appropriate number, given the length of astr.
        """
        # http://stackoverflow.com/a/7867892/190597
        try:
            return struct.unpack(fmt, astr)
        except struct.error:
            flen = struct.calcsize(fmt.replace('*', ''))
            alen = len(astr)
            idx = fmt.find('*')
            before_char = fmt[idx-1]
            n = (alen-flen)/struct.calcsize(before_char)+1
            fmt = ''.join((fmt[:idx-1], str(n), before_char, fmt[idx+1:]))
            return struct.unpack(fmt, astr)
    
    print(unpack('b*','abc'))
    # (97, 98, 99)
    

提交回复
热议问题