当前位置: 首页>>代码示例>>Python>>正文


Python struct._unpack函数代码示例

本文整理汇总了Python中struct._unpack函数的典型用法代码示例。如果您正苦于以下问题:Python _unpack函数的具体用法?Python _unpack怎么用?Python _unpack使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了_unpack函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: code

def code(v, k):
    """
    TEA coder encrypt 64 bits value, by 128 bits key,
    QQ do 16 round TEA.
    To see:
    http://www.ftp.cl.cam.ac.uk/ftp/papers/djw-rmn/djw-rmn-tea.html .

    TEA 加密,  64比特明码, 128比特密钥, qq的TEA算法使用16轮迭代
    具体参看
    http://www.ftp.cl.cam.ac.uk/ftp/papers/djw-rmn/djw-rmn-tea.html
    >>> c = code('abcdefgh', 'aaaabbbbccccdddd')
    >>> b2a_hex(c)
    'a557272c538d3e96'
    """
    n=16  #qq use 16
    delta = 0x9e3779b9
    k = _unpack('>LLLL', k[0:16])
    y, z = _unpack('>LL', v[0:8])
    s = 0
    for i in range(n):
        s += delta
        y += (op &(z<<4))+ k[0] ^ z+ s ^ (op&(z>>5)) + k[1] ;
        y &= op
        z += (op &(y<<4))+ k[2] ^ y+ s ^ (op&(y>>5)) + k[3] ;
        z &= op
    r = _pack('>LL',y,z)
    return r
开发者ID:eignil,项目名称:qqloginjs,代码行数:27,代码来源:tea.py

示例2: decipher

def decipher(v, k):
    """
    TEA decipher, decrypt  64bits value with 128 bits key.
    TEA 解密程序, 用128比特密钥, 解密64比特值

    it's the inverse function of TEA encrypt.
    他是TEA加密函数的反函数.

    >>> c = code('abcdefgh', 'aaaabbbbccccdddd')
    >>> decipher( c, 'aaaabbbbccccdddd')
    'abcdefgh'
    """

    n = 16
    y, z = _unpack('>LL', v[0:8])
    a, b, c, d = _unpack('>LLLL', k[0:16])
    delta = 0x9E3779B9L;
    s = (delta << 4)&op
    for i in xrange(n):
        z -= ((y<<4)+c) ^ (y+s) ^ ((y>>5) + d)
        z &= op
        y -= ((z<<4)+a) ^ (z+s) ^ ((z>>5) + b)
        y &= op
        s -= delta
        s &= op
    return _pack('>LL', y, z)
开发者ID:Javacym,项目名称:python-qq,代码行数:26,代码来源:tea.py

示例3: inet_ntop

def inet_ntop(af, packed_ip):
    """Convert an packed IP address of the given family to string format."""
    if af == AF_INET:
        #   IPv4.
        return inet_ntoa(packed_ip)
    elif af == AF_INET6:
        #   IPv6.
        if len(packed_ip) != 16 or not hasattr(packed_ip, 'split'):
            raise ValueError('invalid length of packed IP address string')

        tokens = ['%x' % i for i in _unpack('>8H', packed_ip)]

        #   Convert packed address to an integer value.
        words = list(_unpack('>8H', packed_ip))
        int_val = 0
        for i, num in enumerate(reversed(words)):
            word = num
            word = word << 16 * i
            int_val = int_val | word

        if 0xffff < int_val <= 0xffffffff or int_val >> 32 == 0xffff:
            #   IPv4 compatible / mapped IPv6.
            packed_ipv4 = _pack('>2H', *[int(i, 16) for i in tokens[-2:]])
            ipv4_str = inet_ntoa(packed_ipv4)
            tokens = tokens[0:-2] + [ipv4_str]

        return ':'.join(_compact_ipv6_tokens(tokens))
    else:
        raise ValueError('unknown address family %d' % af)
开发者ID:0day1day,项目名称:golismero,代码行数:29,代码来源:fbsocket.py

示例4: _parseapetag

def _parseapetag(data):
    '''Parse an APEv2 tag and return a dictionary of tag fields'''
    apeitems = {}
    numitems = _unpack("<i",data[16:20])[0]
    if numitems != _unpack("<i",data[-16:-12])[0]:
        raise TagError, 'Corrupt tag, mismatched header and footer item count' 
    # 32 is size of footer, 11 is minimum item length item
    if numitems > (len(data) - 32)/11:
        raise TagError, 'Corrupt tag, specifies more items that is possible ' \
                        'given space remaining: %i items' % numitems
    curpos = 32
    tagitemend = len(data) - 32
    for x in range(numitems):
        if curpos >= tagitemend:
            raise TagError, 'Corrupt tag, end of tag reached with more items' \
                            'specified'
        item = ApeItem()
        curpos = item.parsetag(data, curpos)
        itemkey = item.key.lower()
        if itemkey in apeitems:
            raise TagError, 'Corrupt tag, duplicate item key: %r' % itemkey
        apeitems[itemkey] = item
    if tagitemend - curpos:
        raise TagError, 'Corrupt tag, parsing complete but not at end ' \
            'of input: %i bytes remaining' % (len(data) - curpos)
    return apeitems
开发者ID:wzssyqa,项目名称:pythonkit,代码行数:26,代码来源:ApeTag.py

示例5: code

def code(v, k):
    n = 16  # qq use 16
    delta = 0x9e3779b9L
    k = _unpack('>LLLL', k[0:16])
    y, z = _unpack('>LL', v[0:8])
    s = 0
    for i in xrange(n):
        s += delta
        y += (op & (z << 4)) + k[0] ^ z + s ^ (op & (z >> 5)) + k[1];
        y &= op
        z += (op & (y << 4)) + k[2] ^ y + s ^ (op & (y >> 5)) + k[3];
        z &= op
    r = _pack('>LL', y, z)
    return r
开发者ID:AliceLanniste,项目名称:python,代码行数:14,代码来源:Tea.py

示例6: _get_clock

def _get_clock():
    global _static_last_sec,_static_last_msec,_static_adjustment,_static_clock_seq
    sec,msec = _gettimeofday()
    try_again = True
    while try_again:
        try_again = False
        if _static_last_sec==0 and _static_last_msec==0:
            _static_clock_seq = _unpack(">H",_get_random_bytes(2))[0] & 0x1FFF
            _static_last_sec = sec - 1
            _static_last_msec = msec
        if sec < _static_last_sec or ((sec == _static_last_sec) and (msec < _static_last_msec)):
            _static_clock_seq = (_static_clock_seq+1) & 0x1FFF
            _static_adjustment = 0
            _static_last_sec = sec
            _static_last_msec = msec
        elif sec == _static_last_sec and msec == _static_last_msec:
            if _static_adjustment >= _MAX_ADJUSTMENT:
                try_again = True
            else:
                _static_adjustment += 1
        else:
            _static_adjustment = 0
            _static_last_sec = sec
            _static_last_msec = msec
    clock_reg = msec*10 + _static_adjustment
    clock_reg = (clock_reg + sec*10000000) & 0xFFFFFFFFFFFFFFFFL
    clock_reg = (clock_reg + (((0x01B21DD2L) << 32) + 0x13814000L)) & 0xFFFFFFFFFFFFFFFFL
    return (clock_reg >> 32),(clock_reg & 0xFFFFFFFFL),_static_clock_seq
开发者ID:PauloJava2016,项目名称:Solfege,代码行数:28,代码来源:uuid.py

示例7: _pkt_R

    def _pkt_R(self):
        #
        # Startup Response
        #
        code = _unpack('!i', self.__read_bytes(4))[0]
        if code == 0:
            self.__authenticated = 1
            #print 'Authenticated!'
        elif code == 1:
            raise InterfaceError('Kerberos V4 authentication is required by server, but not supported by this client')
        elif code == 2:
            raise InterfaceError('Kerberos V5 authentication is required by server, but not supported by this client')
        elif code == 3:
            self.__send(_pack('!i', len(self.__passwd)+5) + self.__passwd + '\0')
        elif code == 4:
            salt = self.__read_bytes(2)
            try:
                import crypt
            except:
                raise InterfaceError('Encrypted authentication is required by server, but Python crypt module not available')
            cpwd = crypt.crypt(self.__passwd, salt)
            self.__send(_pack('!i', len(cpwd)+5) + cpwd + '\0')
        elif code == 5:
            import md5

            m = md5.new(self.__passwd + self.__userid).hexdigest()
            m = md5.new(m + self.__read_bytes(4)).hexdigest()
            m = 'md5' + m + '\0'
            self.__send(_pack('!i', len(m)+4) + m)
        else:
            raise InterfaceError('Unknown startup response code: R%d (unknown password encryption?)' % code)
开发者ID:seanjensengrey,项目名称:bpgsql,代码行数:31,代码来源:bpgsql.py

示例8: _get_random_bytes

def _get_random_bytes(n):
    reader = _get_random_reader()
    buf = ''
    if reader:
        loose_counter = 0
        while len(buf) != n:
            buf += reader(n)

            if loose_counter > 10:
                break
            loose_counter += 1
    d = n-len(buf)

    if d>0:
        buf += '\0'*d

    if n==16:
        fmt = _fmt_16

    elif n==6:
        fmt = _fmt_6

    elif n==2:
        fmt = _fmt_2

    else:
        fmt = ">%sB" % n
    return _pack(fmt,*tuple(map(_randomize_byte,_unpack(fmt,buf))))
开发者ID:RannyeriDev,项目名称:Solfege,代码行数:28,代码来源:uuid.py

示例9: _pkt_T

    def _pkt_T(self):
        #
        # Row Description
        #
        nFields = _unpack("!h", self.__read_bytes(2))[0]
        descr = []
        for i in range(nFields):
            fieldname = self.__read_string()
            oid, type_size, type_modifier = _unpack("!ihi", self.__read_bytes(10))
            descr.append((fieldname, oid, type_size, type_modifier))

        # Save the field description list
        self.__current_result.set_description(descr)

        # build a list of field conversion functions we can use against each row
        self.__current_result.conversion = [self.__type_oid_conversion.get(d[1], _identity) for d in descr]
开发者ID:ddimmich,项目名称:Cubulus,代码行数:16,代码来源:bpgsql.py

示例10: read_n_bytes

def read_n_bytes(fileHandle, formatChar):
    """read n bytes from file. The number of bytes read is specified by the
    ``formatChar``
    
    Parameters
    ----------
    fileHandle : object
        file handle object
    formatChar : string
        format character -- 'c' (1), 'h' (2), 'i' (4), 'I' (4), 'd' (8), 'f' (4)
        
    Returns
    -------
    nbytes : 
    """
    nbytes = None    
    bytes2read = {'c':1, 'h':2, 'i':4, 'I':4, 'd':8, 'f':4}    
    packedBytes = fileHandle.read(bytes2read[formatChar])
    if packedBytes:
        try:
            nbytes = _unpack(formatChar, packedBytes)[0]
        except Exception as e:
            print("Reading bytes from file failed at position {}".format(fileHandle.tell()))
            print("packedBytes = {} of len {}".format(packedBytes, len(packedBytes)))
            raise e
    return nbytes 
开发者ID:indranilsinharoy,项目名称:PyZDDE,代码行数:26,代码来源:zfileutils.py

示例11: get_firmware

def get_firmware(device):
	"""Reads a device's firmware info.

	:returns: a list of FirmwareInfo tuples, ordered by firmware layer.
	"""
	count = feature_request(device, FEATURE.FIRMWARE)
	if count:
		count = ord(count[:1])

		fw = []
		for index in range(0, count):
			fw_info = feature_request(device, FEATURE.FIRMWARE, 0x10, index)
			if fw_info:
				level = ord(fw_info[:1]) & 0x0F
				if level == 0 or level == 1:
					name, version_major, version_minor, build = _unpack(b'!3sBBH', fw_info[1:8])
					version = '%02X.%02X' % (version_major, version_minor)
					if build:
						version += '.B%04X' % build
					extras = fw_info[9:].rstrip(b'\x00') or None
					fw_info = _FirmwareInfo(FIRMWARE_KIND[level], name.decode('ascii'), version, extras)
				elif level == FIRMWARE_KIND.Hardware:
					fw_info = _FirmwareInfo(FIRMWARE_KIND.Hardware, '', ord(fw_info[1:2]), None)
				else:
					fw_info = _FirmwareInfo(FIRMWARE_KIND.Other, '', '', None)

				fw.append(fw_info)
				# _log.debug("device %d firmware %s", devnumber, fw_info)
		return tuple(fw)
开发者ID:Nek-,项目名称:Solaar,代码行数:29,代码来源:hidpp20.py

示例12: parsetag

 def parsetag(self, data, curpos):
     '''Parse next tag from data string, starting at current position'''
     del self[:]
     itemlength = _unpack("<i",data[curpos:curpos+4])[0]
     if itemlength < 0:
         raise TagError, 'Corrupt tag, invalid item length at position ' \
                         '%i: %i bytes' % (curpos, itemlength)
     if data[curpos+4:curpos+7] != '\x00\x00\x00':
         raise TagError, 'Corrupt tag, invalid item flags, bits 8-31 ' \
                         'nonzero at position %i' % curpos
     type, readonly = divmod(ord(data[curpos+7]), 2)
     if type > 3:
         raise TagError, 'Corrupt tag, invalid item flags, bits 3-7 ' \
                         'nonzero at position %i' % curpos
     self.type = _apeitemtypes[type]
     self.readonly = bool(readonly)
     curpos += 8
     keyend = data.find("\x00", curpos)
     if keyend < curpos:
         raise TagError, 'Corrupt tag, unterminated item key at position ' \
                         '%i' % curpos
     itemkey = data[curpos:keyend]
     if not self.validkey(itemkey):
         raise TagError, 'Corrupt tag, invalid item key at position ' \
                         '%i: %r' % (curpos, itemkey)
     self.key = itemkey
     curpos = keyend + itemlength + 1
     itemvalue = data[keyend+1:curpos]
     if self.type == 'utf8' or self.type == 'external':
         self.extend(itemvalue.decode('utf8').split('\x00'))
     else:
         self.append(itemvalue)
     return curpos
开发者ID:wzssyqa,项目名称:pythonkit,代码行数:33,代码来源:ApeTag.py

示例13: lo_create

    def lo_create(self, mode=INV_READ|INV_WRITE):
        """
        Return the oid of a new Large Object, created with the specified mode

        """
        if not self.__lo_funcs:
            self.__lo_init()
        r = self.funcall(self.__lo_funcs['lo_creat'], mode)
        return _unpack('!i', r)[0]
开发者ID:seanjensengrey,项目名称:bpgsql,代码行数:9,代码来源:bpgsql.py

示例14: decipher

def decipher(v, k):
    """
    TEA decipher, decrypt  64bits value with 128 bits key.
    TEA 解密程序, 用128比特密钥, 解密64比特值
    """
    n = 16
    y, z = _unpack('>LL', v[0:8]) 
    a, b, c, d = _unpack('>LLLL', k[0:16])
    delta = 0x9E3779B9L
    s = (delta << 4)&op 
    for i in xrange(n):
        z -= ((y << 4) + c) ^ (y + s) ^ ((y >> 5) + d)
        z &= op
        y -= ((z << 4) + a) ^ (z + s) ^ ((z >> 5) + b)
        y &= op
        s -= delta
        s &= op
    return _pack('>LL', y, z)
开发者ID:johncanlam,项目名称:pcqq,代码行数:18,代码来源:Crypt.py

示例15: libuuid_generate

def libuuid_generate():
    """Generate a UUID with libuuid using the best available method.
    This will raise an exception if libuuid is not available.
    """
    buf = _pack(">16s","")
    out = _pack(">37s","")
    _libuuid.call("uuid_generate",buf)
    _libuuid.call("uuid_unparse",buf,out)
    return _unpack(">36sB",out)[0]
开发者ID:PauloJava2016,项目名称:Solfege,代码行数:9,代码来源:uuid.py


注:本文中的struct._unpack函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。