本文整理汇总了Python中bytearray函数的典型用法代码示例。如果您正苦于以下问题:Python bytearray函数的具体用法?Python bytearray怎么用?Python bytearray使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了bytearray函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_select_with_key_and_multiple_bins_to_select_policy_key_digest
def test_select_with_key_and_multiple_bins_to_select_policy_key_digest(self
):
key = ('test', 'demo', None, bytearray("asd;as[d'as;djk;uyfl",
"utf-8"))
rec = {
'a': ["nanslkdl", 1, bytearray("asd;as[d'as;d", "utf-8")],
'b': {"key": "asd';q;'1';"},
'c': 1234,
'd': '[email protected]#@#$QSDAsd;as'
}
TestSelect.client.put(key, rec)
bins_to_select = ['c', 'd']
policy = {'timeout': 1000, 'key': aerospike.POLICY_KEY_DIGEST}
key, meta, bins = TestSelect.client.select(key, bins_to_select, policy)
assert bins == {'c': 1234, 'd': '[email protected]#@#$QSDAsd;as'}
assert key == ('test', 'demo', None,
bytearray(b"asd;as[d\'as;djk;uyfl"))
assert meta != None
key = ('test', 'demo', None, bytearray("asd;as[d'as;djk;uyfl",
"utf-8"))
TestSelect.client.remove(key)
示例2: test_with_bytearray
def test_with_bytearray(self):
try:
h = hmac.HMAC(bytearray(b"key"), bytearray(b"hash this!"),
digestmod="md5")
except Exception:
self.fail("Constructor call with bytearray arguments raised exception.")
self.assertEqual(h.hexdigest(), '34325b639da4cfd95735b381e28cb864')
示例3: testProcedureWithBinaryAndFloatParameters
def testProcedureWithBinaryAndFloatParameters(self):
if self.dsn == "ODBC":
with udaExec.connect(self.dsn, username=self.username,
password=self.password) as conn:
self.assertIsNotNone(conn)
for r in conn.execute(
"""REPLACE PROCEDURE testProcedure1
(INOUT p1 VARBYTE(128), OUT p2 VARBYTE(128),
INOUT p3 FLOAT, OUT p4 FLOAT, OUT p5 TIMESTAMP)
BEGIN
SET p2 = p1;
SET p4 = p3;
SET p5 = CURRENT_TIMESTAMP;
END;"""):
logger.info(r)
result = conn.callproc(
"testProcedure1",
(teradata.InOutParam(bytearray([0xFF]), "p1"),
teradata.OutParam("p2"),
teradata.InOutParam(float("inf"), "p3"),
teradata.OutParam("p4", dataType="FLOAT"),
teradata.OutParam("p5", dataType="TIMESTAMP")))
self.assertEqual(result.p1, bytearray([0xFF]))
self.assertEqual(result.p2, result.p1)
self.assertEqual(result.p3, float('inf'))
self.assertEqual(result.p4, result.p3)
示例4: _receive
def _receive(self, cls):
message = bytearray(self.socket.recv(max(BUFFER_SIZE, HEADER_SIZE + 2)))
if len(message) < HEADER_SIZE + 2:
raise ProtocolException("Unable to read header")
message_length = 0
for i in xrange(0, HEADER_SIZE):
message_length = message_length << 8 | message[i]
if message[HEADER_SIZE] != PROTOCOL_VERSION:
raise ProtocolException("Wrong protocol 0x%X expected 0x%X" % (message[HEADER_SIZE], PROTOCOL_VERSION))
header_length = message[HEADER_SIZE + 1]
while len(message) < HEADER_SIZE + 2 + header_length:
message.extend(self.socket.recv(BUFFER_SIZE))
(sequence, offset) = read_integer(message, HEADER_SIZE + 2)
if sequence != self.sequence:
raise ProtocolException("Invalid sequence %d expected %d" % (sequence, self.sequence))
(status, offset) = read_integer(message, offset)
if status != 0:
raise ProtocolException("Bad status: 0x%X" % status)
bytes_to_read = message_length - len(message) + HEADER_SIZE
while bytes_to_read > 0:
chunk = bytearray(self.socket.recv(bytes_to_read))
bytes_to_read -= len(chunk)
message.extend(chunk)
if len(chunk) == 0:
break
return cls(**{
'message': message,
'offset': offset
})
示例5: writeData
def writeData(self,f):
self.offset=f.tell();
print("BindShape "+str(len(self.bindShape)));
for b in self.bindShape:
f.write(struct.pack("<f",b));
f.write(struct.pack("<I",len(self.joints)));#joints
for j in self.joints:
f.write(struct.pack("<I",len(j.reference)+1));#mesh
f.write(bytearray('#',"ascii"));
f.write(bytearray(j.reference,"ascii"));
f.write(struct.pack("<I",len(self.joints)*16));#joints
for b in self.jointBindPoses:
f.write(struct.pack("<f",b));
#Omit bounding box
#f.write(struct.pack("<f",0));#Omit bounding box
#f.write(struct.pack("<f",0));#Omit bounding box
#f.write(struct.pack("<f",0));#Omit bounding box
#f.write(struct.pack("<f",0));#Omit bounding box
#f.write(struct.pack("<f",0));#Omit bounding box
#f.write(struct.pack("<f",0));#Omit bounding box
#Omit bounding sphere
#f.write(struct.pack("<f",0));#Omit bounding sphere
#f.write(struct.pack("<f",0));#Omit bounding sphere
#f.write(struct.pack("<f",0));#Omit bounding sphere
#f.write(struct.pack("<f",0));#Omit bounding sphere
return ;
示例6: decint
def decint(raw, forward=True):
'''
Read a variable width integer from the bytestring or bytearray raw and return the
integer and the number of bytes read. If forward is True bytes are read
from the start of raw, otherwise from the end of raw.
This function is the inverse of encint above, see its docs for more
details.
'''
val = 0
byts = bytearray()
src = bytearray(raw)
if not forward:
src.reverse()
for bnum in src:
byts.append(bnum & 0b01111111)
if bnum & 0b10000000:
break
if not forward:
byts.reverse()
for byte in byts:
val <<= 7 # Shift value to the left by 7 bits
val |= byte
return val, len(byts)
示例7: test_remove_with_policy_key_digest
def test_remove_with_policy_key_digest(self):
"""
Invoke remove() with policy_key_digest
"""
key = ( 'test', 'demo', None, bytearray("asd;as[d'as;djk;uyfl",
"utf-8"))
meta = {
'gen' : 0
}
policy = {
'timeout': 1000,
'retry': aerospike.POLICY_RETRY_ONCE,
'key': aerospike.POLICY_KEY_DIGEST
}
retobj = TestRemove.client.put(key, policy)
assert retobj == 0L
retobj = TestRemove.client.remove(key, meta, policy)
assert retobj == 0L
(key, meta, bins) = TestRemove.client.get(key)
assert key == ('test', 'demo', None,
bytearray(b"asd;as[d\'as;djk;uyfl"))
assert meta == None
assert bins == None
示例8: __init__
def __init__(self, length, data_source=None):
"""Initiate section object.
Args:
length: Amount of data the section can store in bytes.
data_source: Should provide a read function to read in the initial
data of the section.
Default is None.
Raises:
IOError: If data_source was not able to provide the whole initial
data.
"""
if data_source is None:
self._data = bytearray(length)
self._last_free = 0
else:
data = data_source.read(length)
self._data = bytearray(data)
if len(data) < length:
raise IOError("expected %i bytes, but got only %i" %
(length, len(data)))
self._last_free = self._find_last_free_chunk()
示例9: main
def main():
global i
global j
if (4 != len(sys.argv)):
usage()
sys.exit(-1)
key_file = open(sys.argv[1], "rb")
msg_file = open(sys.argv[2], "rb")
out_file = open(sys.argv[3], "wb")
key_file.seek(0, 2)
key_len = key_file.tell()
key_file.seek(0, 0)
key_bytearray = bytearray(key_file.read(key_len))
key_file.close()
msg_file.seek(0, 2)
msg_len = msg_file.tell()
msg_file.seek(0, 0)
msg_bytearray = bytearray(msg_file.read(msg_len))
msg_file.close()
S = KSA(key_bytearray)
out_list = []
i = 0
j = 0
for n in msg_bytearray:
K = PRGA(S)
out_list.append(n ^ K)
dumphex("enc", out_list)
out_file.write(bytearray(out_list))
out_file.close()
示例10: CreateRequestV4
def CreateRequestV4():
# Update the call ID
config['call_id'] += 1
# Create KMS Client Request Base
requestBase = CreateRequestBase()
# Create Hash
hashed = str(kmsRequestV4.main(bytearray(requestBase)))
# Generate Request
bodyLength = len(requestBase) + len(hashed)
if bodyLength % 8 == 0:
paddingLength = 0
else:
paddingLength = 8 - bodyLength % 8
v4Data = {
"BodyLength" : bodyLength,
"BodyLength2" : bodyLength,
"Hash" : hashed,
"Padding" : str(bytearray(functions.arrayFill([], paddingLength, 0x00)))
}
logging.debug("Request V4 Data:", v4Data)
request = str()
request += struct.pack('<I',v4Data["BodyLength"])
request += struct.pack('<I',v4Data["BodyLength2"])
request += requestBase
request += v4Data["Hash"]
request += v4Data["Padding"]
logging.debug("Request V4:", binascii.b2a_hex(request), len(request))
return request
示例11: __extractBytes
def __extractBytes(self, input, start, end, mode):
"""
Private method to extract a range of bytes from the input.
@param input input data (bytes)
@param start start index (integer)
@param end end index (integer)
@param mode mode of operation (0, 1, 2)
@return extracted bytes (bytearray)
"""
if end - start > 16:
end = start + 16
if mode == self.ModeOfOperation["CBC"]:
ar = bytearray(16)
else:
ar = bytearray()
i = start
j = 0
while len(ar) < end - start:
ar.append(0)
while i < end:
ar[j] = input[i]
j += 1
i += 1
return ar
示例12: _bmp_to_raw
def _bmp_to_raw(self, bmpfile):
"""Converts a 16bpp, RGB 5:6:5 bitmap to a raw format bytearray."""
data_offset = self._le_unpack(bytearray(bmpfile[0x0a:0x0d]))
width = self._le_unpack(bytearray(bmpfile[0x12:0x15]))
height = self._le_unpack(bytearray(bmpfile[0x16:0x19]))
bpp = self._le_unpack(bytearray(bmpfile[0x1c:0x1d]))
if bpp != 16:
raise IOError("Image is not 16bpp")
if (width != 36 or height != 36) and (width != 320 or height != 240):
raise IOError("Image dimensions must be 36x36 or 320x240 (not %dx%d)" % (width, height))
raw_size = width * height * 2
rawfile = bytearray(b'\x00' * (raw_size + 8))
rawfile[0:8] = [16, 16, bmpfile[0x13], bmpfile[0x12], bmpfile[0x17], bmpfile[0x16], 1, 27]
raw_index = 8
for y in range(0, height):
current_index = (width * (height - (y + 1)) * 2) + data_offset
for k in range(0, width):
rawfile[raw_index] = bmpfile[current_index + 1]
rawfile[raw_index + 1] = bmpfile[current_index]
raw_index += 2
current_index += 2
return rawfile
示例13: test_select_with_unicode_value
def test_select_with_unicode_value(self):
key = ('test', 'demo', 'aa')
rec = {
'a': ["nanslkdl", 1, bytearray("asd;as[d'as;d", "utf-8")],
'b': {"key": "asd';q;'1';"},
'c': 1234,
'd': '[email protected]#@#$QSDAsd;as'
}
assert 0 == TestSelect.client.put(key, rec)
bins_to_select = ['a']
key, meta, bins = TestSelect.client.select(key, bins_to_select)
assert bins == {
'a': ["nanslkdl", 1, bytearray("asd;as[d'as;d", "utf-8")]
}
assert meta != None
assert key != None
key = ('test', 'demo', 'aa')
TestSelect.client.remove(key)
示例14: serialize_tail
def serialize_tail(self):
msg = super(BMPStatisticsReport, self).serialize_tail()
stats_count = len(self.stats)
msg += bytearray(struct.pack('!I', stats_count))
for v in self.stats:
t = v['type']
if t == BMP_STAT_TYPE_REJECTED or \
t == BMP_STAT_TYPE_DUPLICATE_PREFIX or \
t == BMP_STAT_TYPE_DUPLICATE_WITHDRAW or \
t == BMP_STAT_TYPE_INV_UPDATE_DUE_TO_CLUSTER_LIST_LOOP or \
t == BMP_STAT_TYPE_INV_UPDATE_DUE_TO_AS_PATH_LOOP or \
t == BMP_STAT_TYPE_INV_UPDATE_DUE_TO_ORIGINATOR_ID or \
t == BMP_STAT_TYPE_INV_UPDATE_DUE_TO_AS_CONFED_LOOP:
valuepackstr = 'I'
elif t == BMP_STAT_TYPE_ADJ_RIB_IN or \
t == BMP_STAT_TYPE_LOC_RIB:
valuepackstr = 'Q'
else:
continue
v['len'] = struct.calcsize(valuepackstr)
msg += bytearray(struct.pack(self._TLV_PACK_STR + valuepackstr,
t, v['len'], v['value']))
return msg
示例15: set_color
def set_color(self, channel=0, index=0, red=0, green=0, blue=0, name=None, hex=None):
"""Set the color to the device as RGB
Args:
red: Red color intensity 0 is off, 255 is full red intensity
green: Green color intensity 0 is off, 255 is full green intensity
blue: Blue color intensity 0 is off, 255 is full blue intensity
name: Use CSS colour name as defined here: http://www.w3.org/TR/css3-color/
hex: Specify color using hexadecimal color value e.g. '#FF3366'
"""
red, green, blue = self._determine_rgb(red=red, green=green, blue=blue, name=name, hex=hex)
r = int(round(red, 3))
g = int(round(green, 3))
b = int(round(blue, 3))
if self.inverse:
r, g, b = 255 - r, 255 - g, 255 - b
if index == 0 and channel == 0:
control_string = bytes(bytearray([0, r, g, b]))
self._usb_ctrl_transfer(0x20, 0x9, 0x0001, 0, control_string)
else:
control_string = bytes(bytearray([0, channel, index, r, g, b]))
self._usb_ctrl_transfer(0x20, 0x9, 0x0005, 0, control_string)