本文整理汇总了Python中bitstring.BitStream.read方法的典型用法代码示例。如果您正苦于以下问题:Python BitStream.read方法的具体用法?Python BitStream.read怎么用?Python BitStream.read使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类bitstring.BitStream
的用法示例。
在下文中一共展示了BitStream.read方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: uncompress_golomb_coding
# 需要导入模块: from bitstring import BitStream [as 别名]
# 或者: from bitstring.BitStream import read [as 别名]
def uncompress_golomb_coding(coded_bytes, hash_length, M):
"""Given a bytstream produced using golomb_coded_bytes, uncompress it."""
ret_list = []
instream = BitStream(
bytes=coded_bytes, length=len(coded_bytes) * 8)
hash_len_bits = hash_length * 8
m_bits = int(math.log(M, 2))
# First item is a full hash value.
prev = instream.read("bits:%d" % hash_len_bits)
ret_list.append(prev.tobytes())
while (instream.bitpos + m_bits) <= instream.length:
# Read Unary-encoded value.
read_prefix = 0
curr_bit = instream.read("uint:1")
while curr_bit == 1:
read_prefix += 1
curr_bit = instream.read("uint:1")
assert curr_bit == 0
# Read r, assuming M bits were used to represent it.
r = instream.read("uint:%d" % m_bits)
curr_diff = read_prefix * M + r
curr_value_int = prev.uint + curr_diff
curr_value = Bits(uint=curr_value_int, length=hash_len_bits)
ret_list.append(curr_value.tobytes())
prev = curr_value
return ret_list
示例2: encode
# 需要导入模块: from bitstring import BitStream [as 别名]
# 或者: from bitstring.BitStream import read [as 别名]
def encode(self, in_stream, out_stream):
extra_bits = self.num_bits
bs = BitStream()
try:
while True:
chunk = in_stream.read(self.byte_buffer)
#print >> sys.stderr, 'chunk:', chunk
if(chunk):
bs.append(BitStream(bytes=chunk))
else:
while True:
self.print_index(bs.read(self.int_type), out_stream)
try:
while True:
self.print_index(bs.read(self.int_type), out_stream)
except ReadError, e:
#print >> sys.stderr, 'inner:', e
pass
except ReadError, e:
#print >> sys.stderr, 'outer:', e
extra_bits = bs.len - bs.bitpos
if extra_bits > 0:
#print >> sys.stderr, 'extra_bits:', extra_bits
self.print_index(bs.read('uint:' + str(extra_bits)), out_stream)
else:
extra_bits = self.num_bits
示例3: __init__
# 需要导入模块: from bitstring import BitStream [as 别名]
# 或者: from bitstring.BitStream import read [as 别名]
def __init__(self, chunk_id, size, data):
super(HeaderChunk, self).__init__(chunk_id, size)
data_stream = BitStream(data)
# First two bytes are the format type
self.format_type = data_stream.read('bits:16').int
# Second two bytes are the number of tracks
self.num_of_tracks = data_stream.read('bits:16').int
# Third two bytes are the time division
self.time_division = Bits(data_stream.read('bits:16'))
示例4: RTCM_converter_thread
# 需要导入模块: from bitstring import BitStream [as 别名]
# 或者: from bitstring.BitStream import read [as 别名]
def RTCM_converter_thread(server, port, username, password, mountpoint, rtcm_callback = None):
import subprocess
nt = subprocess.Popen(["./ntripclient",
"--server", server,
"--password", password,
"--user", username,
"--mountpoint", mountpoint ],
stdout=subprocess.PIPE)
"""nt = subprocess.Popen(["./ntrip.py", server, str(port), username, password, mountpoint],
stdout=subprocess.PIPE)"""
if nt is None or nt.stdout is None:
indev = sys.stdin
else:
indev = nt.stdout
print("RTCM using input {}".format(indev))
while True:
sio = indev
d = ord(sio.read(1))
if d != RTCMv3_PREAMBLE:
continue
pack_stream = BitStream()
l1 = ord(sio.read(1))
l2 = ord(sio.read(1))
pack_stream.append(bs.pack('2*uint:8', l1, l2))
pack_stream.read(6)
pkt_len = pack_stream.read(10).uint
pkt = sio.read(pkt_len)
parity = sio.read(3)
if len(pkt) != pkt_len:
print "Length error {} {}".format(len(pkt), pkt_len)
continue
if True: #TODO check parity
for d in pkt:
pack_stream.append(bs.pack('uint:8',ord(d)))
msg = parse_rtcmv3(pack_stream)
if msg is not None and rtcm_callback is not None:
rtcm_callback(msg)
示例5: decompress
# 需要导入模块: from bitstring import BitStream [as 别名]
# 或者: from bitstring.BitStream import read [as 别名]
def decompress(data):
feed = []
pos = 0
binary = BitStream(bytes=data)
binary_length = len(binary.bin)
while binary_length - binary.pos >= (WINDOW_BITS + LENGTH_BITS):
distance = binary.read('uint:%d' % WINDOW_BITS)
c_or_length = binary.read('uint:%d' % LENGTH_BITS)
if distance == 0:
c_or_length = chr(c_or_length)
feed.append([distance, c_or_length])
return feed2text(feed)
示例6: uncompress_delta_diff
# 需要导入模块: from bitstring import BitStream [as 别名]
# 或者: from bitstring.BitStream import read [as 别名]
def uncompress_delta_diff(compressed_input, hash_length):
ret_list = []
instream = BitStream(bytes=compressed_input, length=len(compressed_input) * 8)
hash_len_bits = hash_length * 8
prev = instream.read("bits:%d" % hash_len_bits)
ret_list.append(prev.tobytes())
# Must always have at least 6 bits to read.
while (instream.bitpos + 6) < instream.length:
curr_diff_len = instream.read("uint:6") + 1
curr_diff = instream.read("bits:%d" % curr_diff_len)
curr_item = prev[:hash_len_bits - curr_diff_len] + curr_diff
assert curr_item.length == hash_len_bits
ret_list.append(curr_item.tobytes())
prev = curr_item
return ret_list
示例7: Mem
# 需要导入模块: from bitstring import BitStream [as 别名]
# 或者: from bitstring.BitStream import read [as 别名]
class Mem(object):
def __init__(self):
self.real = BitStream(600*16)
self.jumps = 0
def load(self, file):
self.real = BitStream(filename=file)
def save(self, file):
self.real.tofile(file)
def jump(self, pos):
self.jumps += 1
self.real.bytepos = pos
def read(self, size=16):
return self.real.read(16)
def get(self, pos, size=16):
realpos = pos * 8
return self.real[realpos:realpos+size]
def set(self, pos, bits):
realpos = pos * 8
self.real[realpos:realpos+len(bits)] = bits
@property
def pos(self):
return self.real.bytepos
示例8: adjust_tiles
# 需要导入模块: from bitstring import BitStream [as 别名]
# 或者: from bitstring.BitStream import read [as 别名]
def adjust_tiles(tiles, size, isd_text):
ChunkMap = re.split(r"<ChunkMap>", isd_text)
if len(ChunkMap) != 2:
e = "Previous split should have resulted in 2 strings. {} found".format(len(ChunkMap))
raise NotImplementedError(e)
ChunkMap = ChunkMap[1]
# first 2 characters after <Width> tag in <ChunkMap> => up to 99 chunks (= 1584 x 1584 tiles per island)
(width_tiles, height_tiles) = size #@UnusedVariable
width_chunks = int( re.split(r"<Width>", ChunkMap[:100])[1][:2].strip("<") )
height_chunks = int( re.split(r"<Height>", ChunkMap[:100])[1][:2].strip("<") ) #@UnusedVariable
chunks = re.split(r"<Element>", ChunkMap)[1:]
for i in range(len(chunks)):
VertexResolution = re.split(r"<VertexResolution>", chunks[i])[1][0]
if VertexResolution in ("-", "5"): # -1 => empty chunk
continue
VertexResolution = int(VertexResolution)
HeightMap = re.split(r"HeightMap[^C]*CDATA\[", chunks[i])[1:]
start_x = i%width_chunks
start_z = i//width_chunks
resolution = {4: [ 4, 4],
5: [ 25,15],
6: [142,58]}[VertexResolution]
useful_bytes = 17*17*resolution[1]
load_bytes = resolution[0] + useful_bytes
bits_per_tile = resolution[1] * 8
data = BitStream( bytes=HeightMap [0][:load_bytes][-useful_bytes:] )
read_string = "uint:{}".format(bits_per_tile)
for z in range(16):
for x in range(17):
position = start_z*16*width_tiles + z*240 + start_x*16 + x
d = int( data.read(read_string))
if x != 16 and d == 858993471: #trial and error, 0x3333333f=858993471, 0x33=51, 0x3f=63, 0x3333=13107, 0x333f=13119
tiles[position] = 255
return None
示例9: main
# 需要导入模块: from bitstring import BitStream [as 别名]
# 或者: from bitstring.BitStream import read [as 别名]
def main():
for datum in DATA:
as_hex = ":".join("{:02x}".format(h) for h in datum)
as_bin = ":".join("{:08b}".format(h) for h in datum)
print(as_hex)
print(as_bin)
a = BitStream(datum)
first_mb_in_slice = a.read('ue')
slice_type = a.read('ue')
pic_parameter_set_id = a.read('ue')
frame_num = a.read(9)
print("first-mb-in-slice: {}".format(first_mb_in_slice))
print("slice-type: {}".format(slice_type))
print("pic-parameter-set-id: {}".format(pic_parameter_set_id))
print("frame-num: {}".format(frame_num.int))
示例10: gen
# 需要导入模块: from bitstring import BitStream [as 别名]
# 或者: from bitstring.BitStream import read [as 别名]
def gen():
consonants = "bcdfghjklmnpqrstvwxyz"
vowels = "aeiou"
generated = ""
randdata = subprocess.check_output(["openssl", "rand", "9"])
assert len(randdata) == 9
bs = BitStream(randdata)
generated += consonants[bs.read('int:5') % len(consonants)]
for i in range(5):
generated += vowels[bs.read('int:3') % len(vowels)]
generated += consonants[bs.read('int:5') % len(consonants)]
generated += consonants[bs.read('int:5') % len(consonants)]
return generated
示例11: decompress
# 需要导入模块: from bitstring import BitStream [as 别名]
# 或者: from bitstring.BitStream import read [as 别名]
def decompress(self, data):
bitstream = BitStream(data)
pad = bitstream.read(8).int
# remove pad bits
if pad > 0:
bitstream = bitstream[:-pad]
bitstream.read(8) # false read 1 B to move read pointer
tree_len = bitstream.read(16).int
tree_serial = bitstream.read(tree_len)
tree = HuffmanNode()
tree.deserialize(tree_serial)
dictionary = tree.assign_codes()
dictionary = {v: k for k, v in dictionary.items()} # reverse dict
result = bytearray()
sequence = ""
while True:
try:
bit = bitstream.read(1)
except ReadError:
break
if bit:
sequence += '1'
else:
sequence += '0'
if sequence in dictionary:
result.append(dictionary[sequence])
sequence = ""
return result
示例12: uncompress_golomb_coding
# 需要导入模块: from bitstring import BitStream [as 别名]
# 或者: from bitstring.BitStream import read [as 别名]
def uncompress_golomb_coding(coded_bytes, hash_length, M):
ret_list = []
instream = BitStream(
bytes=coded_bytes, length=len(coded_bytes) * hash_length)
hash_len_bits = hash_length * 8
m_bits = int(math.log(M, 2))
prev = instream.read("bits:%d" % hash_len_bits)
ret_list.append(prev.tobytes())
while instream.bitpos < instream.length:
read_prefix = 0
curr_bit = instream.read("uint:1")
while curr_bit == 1:
read_prefix += 1
curr_bit = instream.read("uint:1")
assert curr_bit == 0
r = instream.read("uint:%d" % m_bits)
curr_diff = read_prefix * M + r
curr_value_int = prev.uint + curr_diff
curr_value = Bits(uint=curr_value_int, length=hash_len_bits)
ret_list.append(curr_value.tobytes())
prev = curr_value
return ret_list
示例13: dataEntryAppend
# 需要导入模块: from bitstring import BitStream [as 别名]
# 或者: from bitstring.BitStream import read [as 别名]
def dataEntryAppend(self, eventLogEntryBitStream:BitStream):
"""
since latset entry is in end of whole ECDA dump,
collect all entries and store in reverse order
:param eventLogEntryBitStream:
:return:
"""
timestampHex = eventLogEntryBitStream.read('hex:{}'.format(32))
eventIdHex = eventLogEntryBitStream.read('hex:{}'.format(16))
eventId = int(eventIdHex, 16)
extraInfo = eventLogEntryBitStream.read('hex:{}'.format(16))
self._dataDict['timestampHex'].append(timestampHex)
##self._dataDict['timestamp'].append(timestamp)
##self._dataDict['timeLast'].append(abs(timestamp-self._time) )
##self._dataDict['timeLastInUs'].append(abs(timestamp - self._time )*self._timeGranunityUs)
##self._time = timestamp
self._dataDict['eventId'].append(eventId)
self._dataDict['eventIdHex'].append(eventIdHex)
self._dataDict['extraInfo'].append(extraInfo)
pass
示例14: decrypt
# 需要导入模块: from bitstring import BitStream [as 别名]
# 或者: from bitstring.BitStream import read [as 别名]
def decrypt(ciphertext, key):
bstream = BitStream()
p, g, y = key[0]
u = key[1]
#trying to improve execution speed
#a_pow_u = mod_exp(ciphertext[1][0], u, p)
#inv_a_pow_u = modinv(a_pow_u, p)
for block in ciphertext[1:]:
#sys.stdout.write(".")
#trying to improve execution speed
a_pow_u = mod_exp(block[0], u, p)
inv_a_pow_u = modinv(a_pow_u, p)
x = (block[1] * inv_a_pow_u) % p
block_size = math.floor(math.log(p,2))
bstream.append('0b' + bin(x)[2:].zfill(int(block_size)))
return bstream.read(ciphertext[0])
示例15: MicroKorgPGM
# 需要导入模块: from bitstring import BitStream [as 别名]
# 或者: from bitstring.BitStream import read [as 别名]
class MicroKorgPGM(MicroKorgAbstractData):
def __init__(self, bitstream):
self.program_bitstream = BitStream(bitstream)
print 'GENERAL'
#bytes 0~11
self.program_name = self.read_bytes(12).bytes
print 'Program name: %s' % self.program_name
#bytes 12,13 (dummy bytes)
self.read_bytes(2)
print 'ARPEGGIO TRIGGER CTRL'
##ARPEGGIO_TRIGGER
#byte 14 !!!BITMAP
length_data = self.get_trigger_length_data()
self.arp_trigger_length = arpeggio.TriggerLength(length_data)
print self.arp_trigger_length
#byte 15
self.arp_trigger_pattern = arpeggio.TriggerPattern(
self.read_bytes())
print self.arp_trigger_pattern
#byte 16 !!!BITMAP
self.voice_mode = arpeggio.VoiceMode(self.get_voice_mode())
print self.voice_mode
#byte 17 !!!BITMAP
scale_key, scale_type = self.get_scale_key_and_type()
self.scale_key = arpeggio.ScaleKey(scale_key)
self.scale_type = arpeggio.ScaleType(scale_type)
print self.scale_key
print self.scale_type
#byte 18 (dummy)
self.read_bytes(1)
print 'DELAY FX'
##DELAY FX
#byte 19 !!!BITMAP
delay_sync, delay_time_base = self.get_delay_sync_and_time_base()
self.delay_sync = delay_fx.Sync(delay_sync)
self.delay_time_base = delay_fx.TimeBase(delay_time_base)
print self.delay_sync
print self.delay_time_base
#byte 20
self.delay_time = delay_fx.Time(self.read_bytes())
print self.delay_time
#byte 21
self.delay_depth = delay_fx.Depth(self.read_bytes())
print self.delay_depth
#byte 22
self.delay_type = delay_fx.Type(self.get_delay_type())
print self.delay_type
print 'MOD FX'
##MOD FX
#byte 23
self.mod_lfo_speed = mod_fx.LFOSpeed(self.read_bytes())
print self.mod_lfo_speed
#byte 24
self.mod_depth = mod_fx.Depth(self.read_bytes())
print self.mod_depth
#byte 25
self.mod_type = mod_fx.Type(self.get_mod_type())
print self.mod_type
print 'EQ'
##EQ
#byte 26
self.eq_hi_freq = eq.HiFreq(self.get_freq())
print self.eq_hi_freq
#byte 27
self.eq_hi_gain = eq.HiGain(self.get_gain())
print self.eq_hi_gain
#byte 28
self.eq_low_freq = eq.LoFreq(self.get_freq())
print self.eq_low_freq
#byte 29
self.eq_low_gain = eq.LoGain(self.get_gain())
print self.eq_low_gain
print 'ARPEGGIO'
##ARPEGGIO
#byte 30 & 31
self.arp_tempo = arpeggio.Tempo(self.read_bytes(2))
print self.arp_tempo
#byte 32 !!!BITMAP
arp_on_off, arp_latch, arp_target, arp_key_sync = self.get_arp_bmp_32()
self.arp_on_off = arpeggio.OnOff(arp_on_off)
self.arp_latch = arpeggio.Latch(arp_latch)
self.arp_target = arpeggio.Target(arp_target)
self.arp_key_sync = arpeggio.KeySync(arp_key_sync)
print self.arp_on_off
print self.arp_latch
print self.arp_target
print self.arp_key_sync
#byte 33 !!!BITMAP
arp_type, arp_range = self.get_arp_type_and_range()
self.arp_type = arpeggio.Type(arp_type)
self.arp_range = arpeggio.Range(arp_range)
print self.arp_type
print self.arp_range
#.........这里部分代码省略.........