本文整理汇总了Python中bitstring.BitArray.tobytes方法的典型用法代码示例。如果您正苦于以下问题:Python BitArray.tobytes方法的具体用法?Python BitArray.tobytes怎么用?Python BitArray.tobytes使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类bitstring.BitArray
的用法示例。
在下文中一共展示了BitArray.tobytes方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: trace
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import tobytes [as 别名]
def trace(request):
from random import randrange
from bitstring import BitArray
trace_recs_num = randrange(2, 5)
trace_recs = []
for i in range(trace_recs_num):
peer_ID = BitArray(int=randrange(0, 1000), length=256)
KX_port = randrange(10000, 20000)
IPv4_address = BitArray(int=randrange(0, 1000), length=32)
IPv6_address = BitArray(int=randrange(0, 1000), length=128)
trace_rec = { 'peer_ID': peer_ID.tobytes(),
'KX_port': KX_port,
'IPv4_address': IPv4_address.tobytes(),
'IPv6_address': IPv6_address.tobytes() }
trace_recs.append(trace_rec)
self.logger.debug('process_dht_request->trace.str(peer_ID): %s' % str(peer_ID))
self.logger.debug('process_dht_request->trace.str(KX_port): %s' % str(KX_port))
self.logger.debug('process_dht_request->trace.str(IPv4_address): %s' % str(IPv4_address))
self.logger.debug('process_dht_request->trace.str(IPv6_address): %s' % str(IPv6_address))
response = { 'trace': trace_recs,
'all_ok': True }
self.logger.debug('process_dht_request->find_value.len(response["trace"]): %s' % len(response['trace']))
return response
示例2: generateConfirmationKey
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import tobytes [as 别名]
def generateConfirmationKey(identitySecret,time,tag=""):
identitysecret = b64decode(identitySecret)
secret = BitArray(bytes=identitysecret,length=len(identitysecret)*8)
if tag != "":
tagBuff = BitArray(bytes=tag,length=len(tag)*8)
buff = BitArray(4*8)
time = int(time)
buff.append(BitArray(int=time,length=32))
if tag != "":
buff.append(tagBuff)
conf_hmac = hmac.new(secret.tobytes(),buff.tobytes(),hashlib.sha1)
return b64encode(conf_hmac.digest())
示例3: amrPayload2Storage_EfficientMode
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import tobytes [as 别名]
def amrPayload2Storage_EfficientMode(payload):
if (amr_type == 'nb'):
# AMR-NR
bitlen = [95, 103, 118, 134, 148, 159, 204, 244, 39]
# print "selected codec is amr nb"
elif (amr_type == 'wb'):
# AMR-WB TS 26.201 - total bits
bitlen = [132, 177, 253, 285, 317, 365, 397, 461, 477, 40]
# print "selected codec is amr wb"
else:
exit(1)
amr = BitArray(bytes=payload)
cmr = amr[0:4]
mode = amr[5:9]
#print(mode.uint)
#assert mode.uint >=0 and mode.uint <=8
if not (mode.uint >= 0 and mode.uint <= 8):
return
else:
qual = amr[9:10]
voice = amr[10:10 + bitlen[mode.uint]]
#print("cmr=%d\tmod=%d\tqual=%d\tvoicebits=%d" % (cmr.uint,mode.uint,qual.uint,voice.len))
storage = BitArray(bin='0')
storage.append(mode)
storage.append(qual)
storage.append('0b00') # padding
assert storage.len == 8, "check length of storage header is one byte"
storage.append(voice)
return storage.tobytes()
示例4: golomb_encode
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import tobytes [as 别名]
def golomb_encode(hashes_list, hash_length, M):
hash_len_bits = hash_length * 8
# Must be sorted for delta diff to make sense
assert sorted(hashes_list)
# Must not contain duplicates.
assert len(hashes_list) == len(set(hashes_list))
m_bits = int(math.log(M, 2))
assert abs(math.log(M, 2) - float(m_bits)) < 0.00001
outarray = BitArray(bytes = hashes_list[0], length=hash_len_bits)
min_is_zero = False
prev = BitArray(bytes = hashes_list[0], length=hash_len_bits)
for curr_hash in hashes_list[1:]:
curr = BitArray(bytes=curr_hash, length=hash_len_bits)
N = curr.uint - prev.uint
q = int(math.floor(N / M))
r = N % M
if q == 0:
outarray.append(Bits(bin='0b0'))
min_is_zero = True
else:
outarray.append(Bits(bin=bin(2**q - 1) + '0'))
outarray.append(Bits(uint=r, length=m_bits))
prev = curr
if not min_is_zero:
print "Inefficient encoding: Minimum is not zero."
return outarray.tobytes()
示例5: initFile
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import tobytes [as 别名]
def initFile(self):
file_name = self.file_to_stream['name']
fout = open(file_name, "wb")
data = BitArray(int(self.file_to_stream_length)*8)
data = data.tobytes()
fout.write(data)
fout.close()
示例6: generateAuthCode
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import tobytes [as 别名]
def generateAuthCode(secret,offset=0):
secret = b64decode(secret)
secret = BitArray(bytes=secret,length=len(secret)*8)
buff = BitArray(8*8)
timestamp = timeOffset(offset)
buff[4*8:] = int(timestamp/30)
auth_hmac = hmac.new(secret.tobytes(),buff.tobytes(),hashlib.sha1)
hashed = auth_hmac.digest()
hashed = BitArray(bytes=hashed,length=len(hashed)*8)
start = hashed[(19*8):(19*8)+8] & BitArray('0x0f')
hash_slice = hashed[start.int*8:(start.int*8)+(4*8)]
fullcode = hash_slice & BitArray("0x7fffffff")
fullcode = fullcode.int
chars = '23456789BCDFGHJKMNPQRTVWXY'
code = ""
for x in range(5):
code += chars[int(fullcode % len(chars))]
fullcode = fullcode/len(chars)
return code
示例7: send_bitfield
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import tobytes [as 别名]
def send_bitfield(self):
"""
Tell the peer all the pieces you have in a really compact form.
"""
# the pieces are compacted in sequence in to bits
field = BitArray(
map(
lambda (sha, piece): sha == piece.digest,
self.torrent.pieces.items()
)
)
self.send_payload(5, field.tobytes())
示例8: initFile
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import tobytes [as 别名]
def initFile(self):
file_name = self.file_to_stream['name']
# Check if File Already Exists, If yes, then Read it.
if os.path.isfile(file_name) == True:
# File Exists
print "File Already Exists. Checking For Partial Streaming"
self.reCheck(file_name)
else :
fout = open(file_name, "wb")
data = BitArray(int(self.file_to_stream_length)*8)
data = data.tobytes()
fout.write(data)
fout.close()
示例9: find_value
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import tobytes [as 别名]
def find_value(request):
# TODO: Do the same as in store request above, and delete the lines below
# TODO: in the algorithm of this function, the peer must decide if it is already storing the key/value pair in question
# by issuing a self.data_server.get(key), and checking the result
from random import randrange
from bitstring import BitArray
content = BitArray(int=randrange(0, 1000), length=256)
self.logger.debug('process_dht_request->find_value.str(content): %s' % str(content))
self.logger.debug('process_dht_request->find_value.len(str(content)): %s' % len(str(content)))
response = { 'content': content.tobytes(),
'all_ok': True }
self.logger.debug('process_dht_request->find_value.len(response["content"]): %s' % len(response['content']))
return response
示例10: send
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import tobytes [as 别名]
def send(self):
toSend = BitArray()
for i in range(0,3):
frequency = BitArray(uint=self.frequencies[i], length=3)
intensity = BitArray(uint=self.intensities[i], length=3)
state = BitArray(uint=1, length=3)
toSend.append(intensity)
toSend.append(frequency)
toSend.append(state)
toSend.append('0b00000')
toSend.append('0x00')
if self.enable_bluetooth:
rospy.loginfo("sending msg(hex): %s" %(toSend))
rospy.loginfo("sending msg(bin): %s"%(toSend.bin))
self.bt.send(self.toConnect, str(toSend.tobytes()))
else:
rospy.logdebug("sending msg: %s" %(toSend))
rospy.logdebug(str(toSend.bin))
示例11: double_DES
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import tobytes [as 别名]
def double_DES(key, plain):
keybits = BitArray(hex = key)
plainbits= BitArray(hex = plain)
if len(keybits) != 112:
print "length of double DES key is not 112 bits!"
return
if len(plainbits) != 64:
print "length of double DES plain text is not 64 bits!"
return
rev_keybytes = ''
for k in keybits.cut(7):
rev_keybytes += (odd_parity[k.bin])
obj1 = DES.new(rev_keybytes[0:8], DES.MODE_ECB)
midbytes = obj1.encrypt(plainbits.tobytes())
obj2 = DES.new(rev_keybytes[8:16], DES.MODE_ECB)
cipherbytes = obj2.encrypt(midbytes)
return BitArray(bytes = cipherbytes).hex
示例12: optimiseScr
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import tobytes [as 别名]
def optimiseScr(data):
dataBits = BitArray(bytes=data)
for block in range(0,3):
addrAttr = 0x1800 + 0x100 * block
addrPixel = 0x0800 * block
for char in range(0,256):
addrAttr2 = 8*(addrAttr + char)
addrPixel2 = 8*(addrPixel + char)
pixelData = dataBits[addrPixel2:addrPixel2+8]
pixelData.append(dataBits[addrPixel2+0x0800:addrPixel2+0x0808])
pixelData.append(dataBits[addrPixel2+0x1000:addrPixel2+0x1008])
pixelData.append(dataBits[addrPixel2+0x1800:addrPixel2+0x1808])
pixelData.append(dataBits[addrPixel2+0x2000:addrPixel2+0x2008])
pixelData.append(dataBits[addrPixel2+0x2800:addrPixel2+0x2808])
pixelData.append(dataBits[addrPixel2+0x3000:addrPixel2+0x3008])
pixelData.append(dataBits[addrPixel2+0x3800:addrPixel2+0x3808])
if pixelData.count(1) >= 32:
# More INK than PAPER in this square
# Flip pixels
pixelData = ~pixelData
dataBits[addrPixel2:addrPixel2+8]=pixelData[0:8]
dataBits[addrPixel2+0x0800:addrPixel2+0x0808]=pixelData[8:16]
dataBits[addrPixel2+0x1000:addrPixel2+0x1008]=pixelData[16:24]
dataBits[addrPixel2+0x1800:addrPixel2+0x1808]=pixelData[24:32]
dataBits[addrPixel2+0x2000:addrPixel2+0x2008]=pixelData[32:40]
dataBits[addrPixel2+0x2800:addrPixel2+0x2808]=pixelData[40:48]
dataBits[addrPixel2+0x3000:addrPixel2+0x3008]=pixelData[48:56]
dataBits[addrPixel2+0x3800:addrPixel2+0x3808]=pixelData[56:64]
# Flip attributes
attribute = dataBits[addrAttr2:addrAttr2+8]
dataBits[addrAttr2:addrAttr2+8]=[
attribute[0],attribute[1],
attribute[5],attribute[6],attribute[7],
attribute[2],attribute[3],attribute[4]
]
data = dataBits.tobytes()
return data
示例13: golomb_encode
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import tobytes [as 别名]
def golomb_encode(hashes_list, hash_length, M):
"""Given a sorted list of fixed-size values, compress it by
using Golomb coding to represent the difference between the values."""
hash_len_bits = hash_length * 8
# Must be sorted for deltas to be small and easily compressable.
assert sorted(hashes_list) == hashes_list
# Must not contain duplicates.
assert len(hashes_list) == len(set(hashes_list))
# M is the tunable parameter.
m_bits = int(math.log(M, 2))
# Make sure that M is a power of 2.
assert M > 0 and not (M & (M - 1))
# First item in the output bit array is the first hash value.
outarray = BitArray(bytes = hashes_list[0], length=hash_len_bits)
# Set to true when the diff value / M == 0.
# If no such value exists then the chosen M is too small, so warn.
min_is_zero = False
prev = BitArray(bytes = hashes_list[0], length=hash_len_bits)
for curr_hash in hashes_list[1:]:
curr = BitArray(bytes=curr_hash, length=hash_len_bits)
N = curr.uint - prev.uint
q = int(math.floor(N / M))
r = N % M
# Unary-encode q.
if q == 0:
outarray.append(Bits(bin='0b0'))
min_is_zero = True
else:
outarray.append(Bits(bin=bin(2**q - 1) + '0'))
# Write r using plain binary representation.
outarray.append(Bits(uint=r, length=m_bits))
prev = curr
if not min_is_zero:
print "Inefficient encoding: Minimum is not zero."
return outarray.tobytes()
示例14: encode
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import tobytes [as 别名]
def encode(self):
"""encoding our file"""
self.map = {}
tree = self.tree_maker()
for i in self.data.keys():
current = tree
code = []
while not (current.getLeftChild() is None and current.getRightChild() is None):
if i in current.getLeftChild().getValue()[1]:
code.append('0')
current = current.getLeftChild()
elif i in current.getRightChild().getValue()[1]:
code.append('1')
current = current.getRightChild()
self.map[i] = ''.join(code)
coded_file = open('map.txt', 'w')
coded_file.write(str(self.map))
coded_file.close()
for i in self.file:
self.coded += self.map[i]
with open('file.bin', 'wb') as f:
b = BitArray(bin=self.coded)
f.write(b.tobytes())
示例15: create_delta_diff
# 需要导入模块: from bitstring import BitArray [as 别名]
# 或者: from bitstring.BitArray import tobytes [as 别名]
def create_delta_diff(hashes_list, hash_length):
# Must be sorted for delta diff to make sense
assert sorted(hashes_list)
# Must not contain duplicates.
assert len(hashes_list) == len(set(hashes_list))
hash_len_bits = hash_length * 8
outarray = BitArray(bytes = hashes_list[0], length=hash_len_bits)
prev = BitArray(bytes = hashes_list[0], length=hash_len_bits)
for curr_hash in hashes_list[1:]:
curr = BitArray(bytes=curr_hash, length=hash_len_bits)
i = 0
while prev[i] == curr[i]:
i += 1
assert i < 64
bits_differ = hash_len_bits - i
assert bits_differ > 0 and bits_differ < 65
outarray.append(Bits(uint=(bits_differ - 1), length=6))
diferring_bits = curr[i:]
#print i, bits_differ, diferring_bits.length
assert bits_differ == diferring_bits.length
outarray.append(diferring_bits)
prev = curr
return outarray.tobytes()