• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python struct.struct_unpack函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: _load_from_file

	def _load_from_file(self,source):
		self.filename = source
		self.wavFile  = wavFile = wave_open(self.filename, "rb")

		channels     = wavFile.getnchannels()
		sampleWidth  = wavFile.getsampwidth()
		samplingRate = wavFile.getframerate()
		numSamples   = wavFile.getnframes()
		compName     = wavFile.getcompname()

		if (channels not in [1,2]):
			msg = "for \"%s\", channels=%d is not supported" \
			    % (self.filename,channels)
			raise UGenError(msg)
		if (sampleWidth not in [1,2]):
			msg = "for \"%s\", sampleWidth=%d is not supported" \
			    % (self.filename,sampleWidth)
			raise UGenError(msg)
		if (samplingRate != UGen.samplingRate):
			msg = "for \"%s\", samplingRate=%s does not match %s" \
			   % (self.filename,samplingRate)
			raise UGenError(msg)
		if (compName != "not compressed"):
			msg = "for \"%s\", compName=\"%s\" is not supported" \
			    % (self.filename,compName)
			raise UGenError(msg)

		self.inChannels  = 0
		self.outChannels = channels
		sampleScale = (1<<(8*sampleWidth-1)) - 1
		if (sampleWidth == 1): packFormat = "b"
		else:                  packFormat = "h"
		if (channels == 2):    packFormat = "2%s" % packFormat

		self._allocate(numSamples)

		if ("Clip" in UGen.debug):
			print >>stderr, "Clip.load(%s)" % self
			print >>stderr, "  channels    = %s" % channels
			print >>stderr, "  numSamples  = %s" % numSamples
			print >>stderr, "  sampleWidth = %s" % sampleWidth
			print >>stderr, "  sampleScale = %s" % sampleScale
			print >>stderr, "  packFormat  = %s" % packFormat

		if (channels == 1):
			for ix in xrange(numSamples):
				sample = wavFile.readframes(1)
				sample = struct_unpack(packFormat,sample)[0]
				if (sample < -sampleScale): sample = -sampleScale
				self._buffer[ix] = sample / float(sampleScale)
		else: # (channels == 2):
			for ix in xrange(numSamples):
				sample = wavFile.readframes(1)
				(sample,sample2) = struct_unpack(packFormat,sample)
				if (sample  < -sampleScale): sample  = -sampleScale
				if (sample2 < -sampleScale): sample2 = -sampleScale
				self._buffer [ix] = sample  / float(sampleScale)
				self._buffer2[ix] = sample2 / float(sampleScale)

		wavFile.close()
开发者ID:zacko-belsch,项目名称:pazookle,代码行数:60,代码来源:buffer.py


示例2: _read_snappy_java_header

    def _read_snappy_java_header(self):
        magic = self.fileobj.read(len(SNAPPY_JAVA_MAGIC))
        if magic != SNAPPY_JAVA_MAGIC:
            raise IOError, 'Not a snappy-java file'

        version = struct_unpack("<H", self._read_exact(2))
        compatible_version = struct_unpack("<H", self._read_exact(2))
开发者ID:masahif,项目名称:snappy_util,代码行数:7,代码来源:snappy_java.py


示例3: read_le_bytes

def read_le_bytes(f, n):
  s = f.read(n)
  if len(s) < n:
    raise ValueError("data malformed")
  if n == 1:
    return ord(s)
  elif n == 2:
    return struct_unpack("<H", s)[0]
  elif n == 3:
    return ord(s[0]) | (ord(s[1]) << 8) | (ord(s[2]) << 16)
  elif n == 4:
    return struct_unpack("<I", s)[0]
  else:
    raise ValueError("number of bytes must be in range [1..4]")
开发者ID:HandyMenny,项目名称:csnappy,代码行数:14,代码来源:pysnappy_decompress.py


示例4: intread

def intread(buf):
    """Unpacks the given buffer to an integer."""
    try:
        if isinstance(buf, int):
            return buf
        length = len(buf)
        if length == 1:
            return buf[0]
        elif length <= 4:
            tmp = buf + b"\x00" * (4 - length)
            return struct_unpack("<I", tmp)[0]
        tmp = buf + b"\x00" * (8 - length)
        return struct_unpack("<Q", tmp)[0]
    except:
        raise
开发者ID:dveeden,项目名称:mysql-connector-python,代码行数:15,代码来源:errors.py


示例5: getAdata

 def getAdata(self):
     if DNS.LABEL_UTF8:
         enc = 'utf8'
     else:
         enc = DNS.LABEL_ENCODING
     x = socket.inet_aton(self.getaddr().decode(enc))
     return struct_unpack("!I", x)[0]
开发者ID:ados1991,项目名称:py3dns,代码行数:7,代码来源:Lib.py


示例6: _binparse_fixed

 def _binparse_fixed(self, read):
     s = struct_unpack(self._struct_format, read(self.arraysize * 2))[0]
     s = s.decode('utf_16_be')
     end = s.find('\0')
     if end != -1:
         return s[:end], False
     return s, False
开发者ID:henrysting,项目名称:astropy,代码行数:7,代码来源:converters.py


示例7: decode_date

def decode_date(encvalue):
    val, = struct_unpack('I', encvalue + b'\x00')
    return date(
        day=val & 0x1F,
        month=(val >> 5) & 0xF,
        year=(val >> 9)
    )
开发者ID:adamchainz,项目名称:mariadb-dyncol,代码行数:7,代码来源:base.py


示例8: addr2bin

def addr2bin(addr):
    # Updated from pyspf
    """Convert a string IPv4 address into an unsigned integer.

    Examples::
    >>> addr2bin('127.0.0.1')
    2130706433

    >>> addr2bin('127.0.0.1') == socket.INADDR_LOOPBACK
    1

    >>> addr2bin('255.255.255.254')
    4294967294L

    >>> addr2bin('192.168.0.1')
    3232235521L

    Unlike old DNS.addr2bin, the n, n.n, and n.n.n forms for IP addresses
    are handled as well::
    >>> addr2bin('10.65536')
    167837696
    >>> 10 * (2 ** 24) + 65536
    167837696

    >>> addr2bin('10.93.512')
    173867520
    >>> 10 * (2 ** 24) + 93 * (2 ** 16) + 512
    173867520
    """
    return struct_unpack("!L", inet_aton(addr))[0]
开发者ID:ados1991,项目名称:py3dns,代码行数:30,代码来源:Lib.py


示例9: decode_time

def decode_time(encvalue):
    if len(encvalue) == 6:
        val, = struct_unpack('Q', encvalue + b'\x00\x00')
        return time(
            microsecond=val & 0xFFFFF,
            second=(val >> 20) & 0x3F,
            minute=(val >> 26) & 0x3F,
            hour=(val >> 32)
        )
    else:  # must be 3
        val, = struct_unpack('I', encvalue + b'\x00')
        return time(
            microsecond=0,
            second=(val) & 0x3F,
            minute=(val >> 6) & 0x3F,
            hour=(val >> 12)
        )
开发者ID:adamchainz,项目名称:mariadb-dyncol,代码行数:17,代码来源:base.py


示例10: ioctl_GWINSZ

 def ioctl_GWINSZ(fd):
     try:
         from fcntl import ioctl as fcntl_ioctl
         import termios
         cr = struct_unpack('hh',
                            fcntl_ioctl(fd, termios.TIOCGWINSZ, '1234'))
         return cr
     except:
         pass
开发者ID:billyprice1,项目名称:dump-scraper,代码行数:9,代码来源:terminalsize.py


示例11: parse

 def parse(self, data):
     """ unpacks iwparam"""
     
     size = struct_calcsize(self.fmt)
     m, e, i, pad = struct_unpack(self.fmt, data[:size])
     # XXX well, its not *the* frequency - we need a better name
     if e == 0:
         return m
     else:
         return float(m)*10**e
开发者ID:kakunbsc,项目名称:enigma2.1,代码行数:10,代码来源:iwlibs.py


示例12: __init__

 def __init__(self, data, range):
     """Initialize the scan result with the access point data"""
     self.iwstruct = Iwstruct()
     self.range = range
     self.bssid = "%02X:%02X:%02X:%02X:%02X:%02X" % struct_unpack('BBBBBB', data[2:8])
     self.essid = None
     self.mode = None
     self.rate = []
     self.quality = Iwquality() 
     self.frequency = None
     self.encode = None
     self.custom = []
     self.protocol = None
开发者ID:kakunbsc,项目名称:enigma2.1,代码行数:13,代码来源:iwlibs.py


示例13: __iter__

    def __iter__(self):
        while 1:
            buf = self.__f.read(8)
            if len(buf) < 8:
                break

            blk_type, blk_len = struct_unpack('<II' if self.__le else '>II', buf)
            buf += self.__f.read(blk_len - 8)

            if blk_type == PCAPNG_BT_EPB:
                epb = EnhancedPacketBlockLE(buf) if self.__le else EnhancedPacketBlock(buf)
                ts = self._tsoffset + (((epb.ts_high << 32) | epb.ts_low) / self._divisor)
                yield (ts, epb.pkt_data)
开发者ID:smutt,项目名称:dpkt,代码行数:13,代码来源:pcapng.py


示例14: _read

    def _read(self, size=1024*30):
        raw_chunk_size = self.fileobj.read(4)
        if not raw_chunk_size:
            return False
        chunk_size = struct_unpack(">L", raw_chunk_size)[0]
        chunk = snappy_uncompress(self._read_exact(chunk_size))
        self.pos += len(chunk)

        if self.extrabuf:
            self.extrabuf += chunk
        else:
            self.extrabuf = chunk

        return True
开发者ID:masahif,项目名称:snappy_util,代码行数:14,代码来源:snappy_java.py


示例15: parse_data

    def parse_data(self, fmt, data):
        """ unpacks raw C data """
        size = struct_calcsize(fmt)
        idx = self.idx

        str = data[idx:idx + size]
        self.idx = idx+size
        value = struct_unpack(fmt, str)

        # take care of a tuple like (int, )
        if len(value) == 1:
            return value[0]
        else:
            return value
开发者ID:kakunbsc,项目名称:enigma2.1,代码行数:14,代码来源:iwlibs.py


示例16: _get_terminal_size_windows

def _get_terminal_size_windows():
    try:
        from ctypes import windll, create_string_buffer
        # stdin handle is -10
        # stdout handle is -11
        # stderr handle is -12
        h = windll.kernel32.GetStdHandle(-12)
        csbi = create_string_buffer(22)
        res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
        if res:
            (bufx, bufy, curx, cury, wattr,
             left, top, right, bottom,
             maxx, maxy) = struct_unpack("hhhhHhhhhhh", csbi.raw)
            sizex = right - left + 1
            sizey = bottom - top + 1
            return sizex, sizey
    except:
        pass
开发者ID:billyprice1,项目名称:dump-scraper,代码行数:18,代码来源:terminalsize.py


示例17: _do_unpack_options

    def _do_unpack_options(self, buf, oo=None):
        self.opts = []
        self.data = ''
        oo = oo or self.__hdr_len__ - 4  # options offset
        ol = self.len - oo - 4  # length

        opts_buf = buf[oo:oo + ol]
        while opts_buf:
            opt = (PcapngOptionLE(opts_buf) if self.__hdr_fmt__[0] == '<'
                   else PcapngOption(opts_buf))
            self.opts.append(opt)

            opts_buf = opts_buf[len(opt):]
            if opt.code == PCAPNG_OPT_ENDOFOPT:
                break

        # duplicate total length field
        self._len = struct_unpack(self.__hdr_fmt__[0] + 'I', buf[-4:])[0]
        if self._len != self.len:
            raise dpkt.UnpackError('length fields do not match')
开发者ID:smutt,项目名称:dpkt,代码行数:20,代码来源:pcapng.py


示例18: unpack16bit

def unpack16bit(s):
    return struct_unpack('!H', s)[0]
开发者ID:tvelazquez,项目名称:theharvester,代码行数:2,代码来源:Lib.py


示例19: _parse_length

 def _parse_length(read):
     return struct_unpack(">I", read(4))[0]
开发者ID:henrysting,项目名称:astropy,代码行数:2,代码来源:converters.py


示例20: __init__

    def __init__(self, fileobj):
        self.name = getattr(fileobj, 'name', '<{0}>'.format(fileobj.__class__.__name__))
        self.__f = fileobj

        shb = SectionHeaderBlock()
        buf = self.__f.read(shb.__hdr_len__)
        if len(buf) < shb.__hdr_len__:
            raise ValueError('invalid pcapng header')

        # unpack just the header since endianness is not known
        shb.unpack_hdr(buf)
        if shb.type != PCAPNG_BT_SHB:
            raise ValueError('invalid pcapng header: not a SHB')

        # determine the correct byte order and reload full SHB
        if shb.bom == BYTE_ORDER_MAGIC_LE:
            self.__le = True
            buf += self.__f.read(_swap32b(shb.len) - shb.__hdr_len__)
            shb = SectionHeaderBlockLE(buf)
        elif shb.bom == BYTE_ORDER_MAGIC:
            self.__le = False
            buf += self.__f.read(shb.len - shb.__hdr_len__)
            shb = SectionHeaderBlock(buf)
        else:
            raise ValueError('unknown endianness')

        # check if this version is supported
        if shb.v_major != PCAPNG_VERSION_MAJOR:
            raise ValueError('unknown pcapng version {0}.{1}'.format(shb.v_major, shb.v_minor,))

        # look for a mandatory IDB
        idb = None
        while 1:
            buf = self.__f.read(8)
            if len(buf) < 8:
                break

            blk_type, blk_len = struct_unpack('<II' if self.__le else '>II', buf)
            buf += self.__f.read(blk_len - 8)

            if blk_type == PCAPNG_BT_IDB:
                idb = (InterfaceDescriptionBlockLE(buf) if self.__le
                       else InterfaceDescriptionBlock(buf))
                break
            # just skip other blocks

        if idb is None:
            raise ValueError('IDB not found')

        # set timestamp resolution and offset
        self._divisor = float(1e6)  # defaults
        self._tsoffset = 0
        for opt in idb.opts:
            if opt.code == PCAPNG_OPT_IF_TSRESOL:
                # if MSB=0, the remaining bits is a neg power of 10 (e.g. 6 means microsecs)
                # if MSB=1, the remaining bits is a neg power of 2 (e.g. 10 means 1/1024 of second)
                opt_val = struct_unpack('b', opt.data)[0]
                pow_num = 2 if opt_val & 0b10000000 else 10
                self._divisor = float(pow_num ** (opt_val & 0b01111111))

            elif opt.code == PCAPNG_OPT_IF_TSOFFSET:
                # 64-bit int that specifies an offset (in seconds) that must be added to the
                # timestamp of each packet
                self._tsoffset = struct_unpack('<q' if self.__le else '>q', opt.data)[0]

        if idb.linktype in dltoff:
            self.dloff = dltoff[idb.linktype]
        else:
            self.dloff = 0

        self.idb = idb
        self.snaplen = idb.snaplen
        self.filter = ''
        self.__iter = iter(self)
开发者ID:smutt,项目名称:dpkt,代码行数:74,代码来源:pcapng.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python struct.unpack函数代码示例发布时间:2022-05-27
下一篇:
Python struct.struct_pack函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap