本文整理汇总了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
示例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
示例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
示例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))
示例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))
示例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()
示例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)
示例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()
示例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
示例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())
示例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())
示例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)
示例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())
示例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
示例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))