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


Python bitstring.ConstBitStream类代码示例

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


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

示例1: parseAxisBlock

def parseAxisBlock(axBlkStr):
	ret = dict()
	if len(axBlkStr) != AX_BLK_SIZE:
		raise ValueError("Invalid passed string length")

	keys = ["status", "switches", "stopCode", "refPos", "motorPos",
	"posError", "auxPos", "vel", "torque", "analog"]

	statusKeys = ["moving", "motionMode1", "motionMode1", "findingEdge",
				  "homing", "homeP1Done", "homeP2Done", "coordMotion",
				  "movingNeg", "contourMode", "slewingMode", "stopping",
				  "finalDecel", "latchArmed", "offOnErrArmed", "motorOff"]

	# The fucking galil is little endian, so [:2] splits off the segment of the string we want, and [::-1] reverses it
	statusBs = ConstBitStream(bytes=axBlkStr[:2][::-1])

	# Status is 16 boolean values packed into a uint_16
	statusVals = statusBs.readlist(["uint:1"]*16)

	# zip flags and names into dict
	zipped = zip(statusKeys, statusVals)

	vals = [dict(zipped)]
	vals.extend(struct.unpack(AX_BLK_PARSE_STR, axBlkStr))

	ret = dict(zip(keys, vals))

	return ret
开发者ID:Caglow,项目名称:PyGalil,代码行数:28,代码来源:drParse.py

示例2: from_bytes

    def from_bytes(cls, bitstream):
        '''
           +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
           |  /|    Priority   |    Weight     |  M Priority   |   M Weight    |
           | L +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
           | o |        Unused Flags     |L|p|R|           Loc-AFI             |
           | c +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
           |  \|                             Locator                           |
		   +-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        '''
        record = cls()

        # Convert to ConstBitStream (if not already provided)
        if not isinstance(bitstream, ConstBitStream):
            if isinstance(bitstream, Bits):
                bitstream = ConstBitStream(auto=bitstream)
            else:
                bitstream = ConstBitStream(bytes=bitstream)

        # Read the priorities and weights
        (record.priority, record.weight, record.m_priority,
         record.m_weight) = bitstream.readlist('4*uint:8')

        # Read over unused flags
        record.reserved = bitstream.read(13)

        # Read the flags
        (record.local,
         record.probed_locator,
         record.reachable) = bitstream.readlist('3*bool')

        # Read the locator
        record.address = read_afi_address_from_bitstream(bitstream)

        return record
开发者ID:SeleneLI,项目名称:LIG_measurement,代码行数:35,代码来源:locator_record.py

示例3: from_bytes

    def from_bytes(cls, bitstream):
        packet = cls()

        # Convert to ConstBitStream (if not already provided)
        if not isinstance(bitstream, ConstBitStream):
            if isinstance(bitstream, Bits):
                bitstream = ConstBitStream(auto=bitstream)
            else:
                bitstream = ConstBitStream(bytes=bitstream)

        # Read the next header type
        packet.next_header = bitstream.read('uint:8')

        # Read the header length, given in multiples of 8 octets
        header_length = bitstream.read('uint:8') + 1

        # Read the options
        options_length = (header_length * 8) - 2
        packet.options = bitstream.read('bytes:%d' % options_length)

        # And the rest is payload
        remaining = bitstream[bitstream.pos:]
        packet.payload = remaining.bytes

        payload_class = protocol_registry.get_type_class(packet.next_header)
        if payload_class:
            packet.payload = payload_class.from_bytes(packet.payload)

        # Verify that the properties make sense
        packet.sanitize()

        return packet
开发者ID:SeleneLI,项目名称:LIG_measurement,代码行数:32,代码来源:hop_by_hop_options_header.py

示例4: __init__

 def __init__(self, src, *args, **kwargs):
     super(EC3SpecificBox,self).__init__(src, *args,**kwargs)
     data = src.read(self.size)
     bs = ConstBitStream(bytes=data)
     self.data_rate = bs.read('uint:13')
     self.num_ind_sub = 1+bs.read('uint:3')
     self.substreams = []
     for i in range(self.num_ind_sub):
         self.substreams.append(EC3SpecificBox.SubStream(bs))
开发者ID:asrashley,项目名称:dash-live,代码行数:9,代码来源:mp4.py

示例5: handle_read

    def handle_read(self):
        #format: 20 bytes in total. Size: intle:16
        #Incomming messages comes with 160 bytes..
        data0 = self.recv(160);
        if data0:            
            data = ConstBitStream(bytes=data0, length=160)
            print "All: %s" % data.bin
 
            msize = data.read('intle:16')
            mtype = data.read('intle:16')
            mtime = data.read('intle:64')
 
            # RA: 
            ant_pos = data.bitpos
            ra = data.read('hex:32')
            data.bitpos = ant_pos
            ra_uint = data.read('uintle:32')
 
            # DEC:
            ant_pos = data.bitpos
            dec = data.read('hex:32')
            data.bitpos = ant_pos
            dec_int = data.read('intle:32')
 
            logging.debug("Size: %d, Type: %d, Time: %d, RA: %d (%s), DEC: %d (%s)" % (msize, mtype, mtime, ra_uint, ra, dec_int, dec))
            (sra, sdec, stime) = coords.eCoords2str(float("%f" % ra_uint), float("%f" % dec_int), float("%f" %  mtime))
 
            #Sends back the coordinates to Stellarium
            self.act_pos(coords.hourStr_2_rad(sra), coords.degStr_2_rad(sdec))
开发者ID:lfortuna,项目名称:TelescopeController,代码行数:29,代码来源:telescope.py

示例6: main

def main():
    test_file = sys.argv[1]
    f = open(os.path.join(os.getcwd(), test_file), "rb")
    s = ConstBitStream(f)
    try:
        file_type = s.read("bytes:3")
        if file_type == "FWS":
            print "Standard SWF"
            print "Version:", s.read("uintle:8")
            print "Size:", s.read("uintle:32"), "bytes"
            s = datatypes.rect(s)
            print "Frame rate: %d.%d" % datatypes.fixed_8(s)
            print "Frame count:", s.read("uintle:16")
            read_tag_headers(s)
        elif file_type == "CWS":
            print "Compressed SWF"
            print "Version:", s.read("uintle:8")
            print "Uncompressed size:", s.read("uintle:32"), "bytes"
            to_decompress = s[64:].tobytes()
            s = ConstBitStream(bytes=zlib.decompress(to_decompress))
            s = datatypes.rect(s)
            print "Frame rate: %d.%d" % datatypes.fixed_8(s)
            print "Frame count:", s.read("uintle:16")
            read_tag_headers(s)
            # print "[Cannot currently parse]"
    finally:
        f.close()
开发者ID:pombredanne,项目名称:py-swf-parse,代码行数:27,代码来源:header.py

示例7: handle_read

	def handle_read(self):
		#format: 20 bytes in total. Size: intle:16
		#Incomming messages comes with 160 bytes..
		data0 = self.recv(160);
		if data0:			
			data = ConstBitStream(bytes=data0, length=160)
			#print "All: %s" % data.bin
			
			msize = data.read('intle:16')
			mtype = data.read('intle:16')
			mtime = data.read('intle:64')
			
			# RA: 
			ant_pos = data.bitpos
			ra = data.read('hex:32')
			data.bitpos = ant_pos
			ra_uint = data.read('uintle:32')
			
			# DEC:
			ant_pos = data.bitpos
			dec = data.read('hex:32')
			data.bitpos = ant_pos
			dec_int = data.read('intle:32')
			
			#______ Testing:
			# Sends back to Stellarium the received coordinates, in order to update the field of view indicator
			(sra, sdec, stime) = coords.eCoords2str(float("%f" % ra_uint), float("%f" % dec_int), float("%f" %  mtime))
			self.act_pos(coords.hourStr_2_rad(sra), coords.degStr_2_rad(sdec))
			#______ End Testing
			
			# Emits the signal with received equatorial coordinates (for use in external Qt Gui..)
			self.stell_pos_recv.emit("%f" % ra_uint, "%f" % dec_int, "%f" %  mtime)
开发者ID:AishPadmanabha,项目名称:Arduino-Telescope-Control,代码行数:32,代码来源:telescope_server.py

示例8: _parse_binary_feed

    def _parse_binary_feed(self, feed):
        binaryfeed = bytearray(b64decode(feed))
        bitstream = ConstBitStream(binaryfeed)

        payload_encoding = binaryfeed[0]
        if payload_encoding != bitstream.read("uint:8"):
            raise PyiCloudBinaryFeedParseError("Missmatch betweeen binaryfeed and bistream payload encoding")

        ASSET_PAYLOAD = 255
        ASSET_WITH_ORIENTATION_PAYLOAD = 254
        ASPECT_RATIOS = [
            0.75,
            4.0 / 3.0 - 3.0 * (4.0 / 3.0 - 1.0) / 4.0,
            4.0 / 3.0 - 2.0 * (4.0 / 3.0 - 1.0) / 4.0,
            1.25,
            4.0 / 3.0,
            1.5 - 2.0 * (1.5 - 4.0 / 3.0) / 3.0,
            1.5 - 1.0 * (1.5 - 4.0 / 3.0) / 3.0,
            1.5,
            1.5694444444444444,
            1.6388888888888888,
            1.7083333333333333,
            16.0 / 9.0,
            2.0 - 2.0 * (2.0 - 16.0 / 9.0) / 3.0,
            2.0 - 1.0 * (2.0 - 16.0 / 9.0) / 3.0,
            2,
            3,
        ]

        valid_payloads = [ASSET_PAYLOAD, ASSET_WITH_ORIENTATION_PAYLOAD]
        if payload_encoding not in valid_payloads:
            raise PyiCloudBinaryFeedParseError("Unknown payload encoding '%s'" % payload_encoding)

        assets = {}
        while len(bitstream) - bitstream.pos >= 48:
            range_start = bitstream.read("uint:24")
            range_length = bitstream.read("uint:24")
            range_end = range_start + range_length

            previous_asset_id = 0
            for index in range(range_start, range_end):
                aspect_ratio = ASPECT_RATIOS[bitstream.read("uint:4")]

                id_size = bitstream.read("uint:2")
                if id_size:
                    # A size has been reserved for the asset id
                    asset_id = bitstream.read("uint:%s" % (2 + 8 * id_size))
                else:
                    # The id is just an increment to a previous id
                    asset_id = previous_asset_id + bitstream.read("uint:2") + 1

                orientation = None
                if payload_encoding == ASSET_WITH_ORIENTATION_PAYLOAD:
                    orientation = bitstream.read("uint:3")

                assets[index] = PhotoAsset(index, asset_id, aspect_ratio, orientation, self)
                previous_asset_id = asset_id

        return assets.values()
开发者ID:RohanNijhawan,项目名称:pyicloud,代码行数:59,代码来源:photos.py

示例9: from_bytes

    def from_bytes(cls, bitstream):
        """
        Parse the given record and update properties accordingly
        """
        record = cls()

        # Convert to ConstBitStream (if not already provided)
        if not isinstance(bitstream, ConstBitStream):
            if isinstance(bitstream, Bits):
                bitstream = ConstBitStream(auto=bitstream)
            else:
                bitstream = ConstBitStream(bytes=bitstream)

        # Read the record TTL
        record.ttl = bitstream.read("uint:32")

        # Store the locator record count until we need it
        referral_count = bitstream.read("uint:8")

        # Store the EID prefix mask length until we need it
        eid_prefix_len = bitstream.read("uint:8")

        # Read the Negative Map_Reply action
        record.action = bitstream.read("uint:3")

        # Read the flags
        (record.authoritative, record.incomplete) = bitstream.readlist("2*bool")

        # Read reserved bits
        record._reserved1 = bitstream.read(11)

        # Read the signature count
        sig_count = bitstream.read("uint:4")

        # Read the map version
        record.map_version = bitstream.read("uint:12")

        # Read the EID prefix
        record.eid_prefix = read_afi_address_from_bitstream(bitstream, eid_prefix_len)

        # Read the locator records
        for dummy in range(referral_count):
            locator_record = LocatorRecord.from_bytes(bitstream)
            record.locator_records.append(locator_record)

        # TODO: Can't handle signatures yet! [LISP-Security]
        if sig_count:
            raise NotImplementedError("Cannot handle signatures yet")

        # Verify that the properties make sense
        record.sanitize()

        return record
开发者ID:hansomesong,项目名称:pylisp,代码行数:53,代码来源:map_referral_record.py

示例10: test_afi_2_with_prefixlen

    def test_afi_2_with_prefixlen(self):
        '''
        Test decoding of AFI 2 (IPv6) prefixes
        '''
        afi_address_hex = '000220010db80102abcd0000000000000000'
        bitstream = ConstBitStream(hex=afi_address_hex)

        address = afi.read_afi_address_from_bitstream(bitstream, 64)

        self.assertEqual(address, IPv6Network(u'2001:db8:102:abcd::/64'))
        self.assertEqual(bitstream.pos, bitstream.len,
                         'unprocessed bits remaining in bitstream')

        new_bitstream = afi.get_bitstream_for_afi_address(address)

        self.assertEqual(new_bitstream.tobytes(), bitstream.tobytes())
开发者ID:SeleneLI,项目名称:LIG_measurement,代码行数:16,代码来源:test_utils_afi.py

示例11: test_afi_1_with_prefixlen

    def test_afi_1_with_prefixlen(self):
        '''
        Test decoding of AFI 1 (IPv4) prefixes
        '''
        afi_address_hex = '0001c0000200'
        bitstream = ConstBitStream(hex=afi_address_hex)

        address = afi.read_afi_address_from_bitstream(bitstream, 24)

        self.assertEqual(address, IPv4Network(u'192.0.2.0/24'))
        self.assertEqual(bitstream.pos, bitstream.len,
                         'unprocessed bits remaining in bitstream')

        new_bitstream = afi.get_bitstream_for_afi_address(address)

        self.assertEqual(new_bitstream.tobytes(), bitstream.tobytes())
开发者ID:SeleneLI,项目名称:LIG_measurement,代码行数:16,代码来源:test_utils_afi.py

示例12: parse_one_frame_from_buffer

  def parse_one_frame_from_buffer(self):
    retry       = True    # until we have one or don't have enough
    errors      = []
    frame       = None
    bits_parsed = 0
    while retry and len(self.buffer) > 0:
      try:
        self.s      = ConstBitStream(bytes=self.buffer)
        frame         = self.parse_frame()
        bits_parsed = self.s.pos
        self.shift_buffer(bits_parsed/8)
        retry = False         # got one, carry on
      except ReadError as e:       # not enough to read, carry on and wait for more
        retry = False
      except ParseError as e: # actual problem with current buffer, need to skip
        errors.append({
          "error"   : e.args[0],
          "buffer"  : list(self.buffer),
          "pos"     : self.s.pos,
          "skipped" : self.skip_bad_buffer_content()
        })

    info = {
      "parsed" : bits_parsed,
      "buffer" : len(self.buffer) * 8,
      "errors" : errors
    }
    return (frame, info)
开发者ID:MOSAIC-LoPoW,项目名称:pyd7a,代码行数:28,代码来源:parser.py

示例13: test_afi_0_without_prefixlen

    def test_afi_0_without_prefixlen(self):
        '''
        Test en/decoding of empty AFI addresses
        '''
        afi_address_hex = '0000'
        bitstream = ConstBitStream(hex=afi_address_hex)

        address = afi.read_afi_address_from_bitstream(bitstream)

        self.assertIsNone(address, 'wrong address')
        self.assertEqual(bitstream.pos, bitstream.len,
                         'unprocessed bits remaining in bitstream')

        new_bitstream = afi.get_bitstream_for_afi_address(address)

        self.assertEqual(new_bitstream.tobytes(), bitstream.tobytes())
开发者ID:SeleneLI,项目名称:LIG_measurement,代码行数:16,代码来源:test_utils_afi.py

示例14: ff

def ff(file, mode='unknown'):
    '''Read header from data file.'''
    infile = open(file, 'r')

    oldheader = infile.read(8)

    # Finds "Dartmouth"
    s = ConstBitStream(filename=file)
    found = s.find('0x446172746d6f757468', bytealigned=True)
    if found:
        print("Found start code at byte offset %d." % found[0])
        # s0f0, length, bitdepth, height, width = s.readlist('hex: 16, uint: 16,
        # uint: 8, 2 * uint: 16')
        # print("Width %d, Height %d" % (width, height))
    else:
        print("No way!!")

    if oldheader[0:6] == "999999" and mode == 'unknown':
        if oldheader[6:8] == "01":
            mode = 'head'
        elif oldheader[6:8] == "04":
            mode = 'tail'
        else:
            print "ff(): Mode not defined in input or old header"
            return(1)
    elif oldheader[0:6] != "999999" and mode != 'tail':
        print "ff(): No valid GGSE header signature."
        return(1)

    if mode == 'head':
        header = infile.read(8184)
    elif mode == 'tail':
        infile.seek(-8192, os.SEEK_END)
        header = infile.read(8192)
    else:
        print "ff(): Unknown mode."
        return(1)

    infile.close()

    try:
        fhead = fs(header)
    except confp.ParsingError or confp.MissingSectionHeaderError:
        print "ff(): error parsing file: No header in " + mode + " of file?"
        fhead = 1

    return fhead
开发者ID:Dartspacephysiker,项目名称:Core-FFT,代码行数:47,代码来源:ggseHeader.py

示例15: testFromFile

 def testFromFile(self):
     s = CBS(filename='test.m1v')
     self.assertEqual(s[0:32].hex, '000001b3')
     self.assertEqual(s.read(8 * 4).hex, '000001b3')
     width = s.read(12).uint
     height = s.read(12).uint
     self.assertEqual((width, height), (352, 288))
开发者ID:AishPadmanabha,项目名称:Arduino-Telescope-Control,代码行数:7,代码来源:test_constbitstream.py


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