本文整理汇总了Python中bitstring.BitStream类的典型用法代码示例。如果您正苦于以下问题:Python BitStream类的具体用法?Python BitStream怎么用?Python BitStream使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了BitStream类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: save
def save(self, filename, font_type = FONT_TYPES.font01, game = GAMES.dr):
data = BitStream(SPFT_MAGIC)
data += BitStream(uintle = len(self.data), length = 32)
mapping_table_len = self.find_max_char() + 1 # zero-indexed so +1 for the size.
mapping_table_start = 0x20
font_table_start = mapping_table_len * 2 + mapping_table_start
data += BitStream(uintle = font_table_start, length = 32)
data += BitStream(uintle = mapping_table_len, length = 32)
data += BitStream(uintle = mapping_table_start, length = 32)
data += UNKNOWN1[game][font_type] + UNKNOWN2
data += self.gen_mapping_table(mapping_table_len)
data += self.gen_font_table()
padding = BitStream(hex = '0x00') * (16 - ((data.len / 8) % 16))
data += padding
f = open(filename, "wb")
data.tofile(f)
f.close()
示例2: uncompress_golomb_coding
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
示例3: Mem
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
示例4: adjust_tiles
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
示例5: parse
def parse(self):
bs = BitStream(filename=self.file_path)
[index_start, extension_data_start] = parse_header(bs)
self.app_info = parse_app_info(bs)
bs.bytepos = index_start
self.indexes = parse_index(bs)
self.parsed = True
示例6: save
def save(self, filename):
data = BitStream(self.magic) + BitStream(uintle = len(self.lines), length = 16)
for line in self.lines:
data += line.to_data()
with open(filename, "wb") as f:
data.tofile(f)
示例7: __init__
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'))
示例8: decompress
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)
示例9: decode
def decode(self, in_stream, out_stream):
bs = BitStream()
dq = deque()
at_least_three = False
for word in self.words_from_file(in_stream):
if not word or word not in self.word_dict:
continue
#print >> sys.stderr, 'word:"', word, '"'
dq.append(self.word_dict[word])
if at_least_three or len(dq) == 3:
bs.append(pack(self.int_type, dq.popleft()))
at_least_three = True
if bs.len > self.bit_buffer:
cut = 0
for byte in bs.cut(self.bit_buffer):
cut += 1
byte.tofile(out_stream)
del bs[:cut * self.bit_buffer]
# dq has to have exactly 2 elements here, the last is the bit length of the first, unless it's 0
#print >> sys.stderr, 'dq:', dq
extra_bits = dq.pop()
bs.append(pack('uint:' + str(extra_bits), dq.popleft()))
bs.tofile(out_stream)
示例10: uncompress_delta_diff
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
示例11: write_char_array
def write_char_array(self, max_length, value):
self.write_int(bit_count(max_length), len(value))
if self._bits.len > 0:
more = 8 - self._bits.len
tail = (BitStream(int=0, length=more) + self._bits).tobytes()
self._bits = BitStream()
self._bytes += tail
self._bytes += value
示例12: main
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))
示例13: gen
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
示例14: decompress
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
示例15: decrypt
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])