本文整理汇总了Python中struct.pack_into函数的典型用法代码示例。如果您正苦于以下问题:Python pack_into函数的具体用法?Python pack_into怎么用?Python pack_into使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了pack_into函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _boot_pkt
def _boot_pkt(socket, host, op, a1, a2, a3, data=None, offset=0, datasize=0):
"""
Packs the given data into the format required by the Boot ROM program that
executes automatically when SpiNNaker is first turned on.
:param socket: stream to write the command to
:param host: hostname of the target SpiNNaker
:param op: boot ROM command
:param arg1: argument 1 -- varies with ``op``
:param arg2: argument 2 -- varies with ``op``
:param arg3: argument 3 -- varies with ``op``
:param data: optional data
:param offset: the offset into the data to start from
:param datasize: the maximum amount of data to write from the data
"""
if data is not None:
pkt_data = numpy.zeros(datasize + 18, dtype=numpy.uint8)
struct.pack_into(">HLLLL", pkt_data, 0, BOOT_PROT_VER, op, a1, a2, a3)
off = 0
readsize = datasize
if (offset + readsize) > data.size:
readsize = data.size - offset
while off < readsize:
the_word = struct.unpack_from("<I", data, offset + off)[0]
struct.pack_into(">I", pkt_data, 18 + off, the_word)
off += 4
socket.sendto(pkt_data, (host, BOOT_PORT))
else:
hdr = struct.pack(">HLLLL", BOOT_PROT_VER, op, a1, a2, a3)
socket.sendto(hdr, (host, BOOT_PORT))
time.sleep(BOOT_DELAY)
示例2: SerializeArray
def SerializeArray(self, value, data_offset, data, handle_offset):
size = (serialization.HEADER_STRUCT.size +
self.sub_type.GetByteSize() * len(value))
data_end = len(data)
position = len(data) + serialization.HEADER_STRUCT.size
data.extend(bytearray(size +
serialization.NeededPaddingForAlignment(size)))
returned_handles = []
to_pack = []
for item in value:
(new_data, new_handles) = self.sub_type.Serialize(
item,
len(data) - position,
data,
handle_offset + len(returned_handles))
to_pack.extend(serialization.Flatten(new_data))
returned_handles.extend(new_handles)
position = position + self.sub_type.GetByteSize()
serialization.HEADER_STRUCT.pack_into(data, data_end, size, len(value))
# TODO(azani): Refactor so we don't have to create big formatting strings.
struct.pack_into(('%s' % self.sub_type.GetTypeCode()) * len(value),
data,
data_end + serialization.HEADER_STRUCT.size,
*to_pack)
return (data_offset, returned_handles)
示例3: sendJoinRoomRequestOIE
def sendJoinRoomRequestOIE(self,roomName):
self.RoomName=roomName # il y'avait self.thisRoomName???
ack_num=0
res=0
ack=0
if (roomName!=ROOM_IDS.MAIN_ROOM):
self.userStatus=userStatus['waitingfMovieRoomUserList']
self.typemsgenvoye="6"
typeMsg=6
msgLength=14
Movie=self.MovieStore.getMovieByTitle(roomName)
print Movie.movieTitle
IpAdressMovie=Movie.movieIpAddress
print IpAdressMovie
MoviePort=Movie.moviePort
buf=ctypes.create_string_buffer(14)
header=(typeMsg<<28)|(ack<<27)|(res<<26)|(ack_num<<13)|(self.seq_num)
Tab=IpAdressMovie.split('.')
print Tab
struct.pack_into(">LHHBBBBH", buf,0,header,msgLength,self.userId,int(Tab[0]),int(Tab[1]),int(Tab[2]),int(Tab[3]),MoviePort)
self.EnvoiMsg(buf)
else:
typeMsg=7
self.userStatus=userStatus['waitingMainRoom']
self.typemsgenvoye="7"
msgLength=8
buf=ctypes.create_string_buffer(8)
header=(typeMsg<<28)|(ack<<27)|(res<<26)|(ack_num<<13)|(self.seq_num)
struct.pack_into(">LHH", buf,0,header,msgLength,self.userId)
self.EnvoiMsg(buf)
print "Request join movie room envoyé"
示例4: pack_into
def pack_into(self, buff, offset):
"""Serialize and write to ``buff`` starting at offset ``offset``.
Intentionally follows the pattern of ``struct.pack_into``
:param buff: The buffer to write into
:param offset: The offset to start the write at
"""
if self.partition_key is None:
fmt = "!BBii%ds" % len(self.value)
args = (self.MAGIC, self.compression_type, -1, len(self.value), self.value)
else:
fmt = "!BBi%dsi%ds" % (len(self.partition_key), len(self.value))
args = (
self.MAGIC,
self.compression_type,
len(self.partition_key),
self.partition_key,
len(self.value),
self.value,
)
struct.pack_into(fmt, buff, offset + 4, *args)
fmt_size = struct.calcsize(fmt)
data = buffer(buff[(offset + 4) : (offset + 4 + fmt_size)])
crc = crc32(data) & 0xFFFFFFFF
struct.pack_into("!I", buff, offset, crc)
示例5: updateDossierCompDescr
def updateDossierCompDescr(self, dossierCompDescrArray, offset, size):
length = size / self.__itemSize
newLength = len(self.__list)
newSize = newLength * self.__itemSize
if self.__isExpanded:
fmt = '<' + self.__itemFormat * newLength
values = []
for item in self.__list:
values += self.__itemToList(item)
if newSize == size:
struct.pack_into(fmt, dossierCompDescrArray, offset, *values)
return (dossierCompDescrArray, newSize)
return (dossierCompDescrArray[:offset] + array('c', struct.pack(fmt, *values)) + dossierCompDescrArray[offset + size:], newSize)
for idx in self.__changed:
if idx < length:
itemOffset = offset + idx * self.__itemSize
struct.pack_into(('<' + self.__itemFormat), dossierCompDescrArray, itemOffset, *self.__itemToList(self.__list[idx]))
self.__changed.clear()
added = self.__list[length:]
if added:
values = []
for item in added:
values += self.__itemToList(item)
fmt = '<' + self.__itemFormat * len(added)
dossierCompDescrArray = dossierCompDescrArray[:offset + size] + array('c', struct.pack(fmt, *values)) + dossierCompDescrArray[offset + size:]
return (dossierCompDescrArray, newSize)
示例6: test_checksum
def test_checksum(self):
"""
This tests the checksum algorithm; if somebody changes the algorithm
this test should catch it. Had to jump through some hoops to do this;
needed to add set_data_length and set_header because we're building our
own header here (the one in PortAgentPacket includes the timestamp
so the checksum is not consistent).
"""
test_data = "This tests the checksum algorithm."
test_length = len(test_data)
self.pap.attach_data(test_data)
# Now build a header
variable_tuple = (0xa3, 0x9d, 0x7a, self.pap.DATA_FROM_DRIVER,
test_length + HEADER_SIZE, 0x0000,
0)
self.pap.set_data_length(test_length)
header_format = '>BBBBHHd'
size = struct.calcsize(header_format)
temp_header = ctypes.create_string_buffer(size)
struct.pack_into(header_format, temp_header, 0, *variable_tuple)
# Now set the header member in PortAgentPacket to the header
# we built
self.pap.set_header(temp_header.raw)
# Now get the checksum and verify it is what we expect it to be.
checksum = self.pap.calculate_checksum()
self.assertEqual(checksum, 2)
示例7: _pack_packet
def _pack_packet(hostname, service, state, output, timestamp):
"""This is more complicated than a call to struct.pack() because we want
to pad our strings with random bytes, instead of with zeros."""
requested_length = struct.calcsize(_data_packet_format)
packet = array.array('c', '\0'*requested_length)
# first, pack the version, initial crc32, timestamp, and state
# (collectively:header)
header_format = '!hxxLLh'
offset = struct.calcsize(header_format)
struct.pack_into('!hxxLLh', packet, 0, PACKET_VERSION, 0, timestamp, state)
# next, pad & pack the hostname
hostname = hostname + '\0'
if len(hostname) < MAX_HOSTNAME_LENGTH:
hostname += get_random_alphanumeric_bytes(MAX_HOSTNAME_LENGTH - len(hostname))
struct.pack_into('!%ds' % (MAX_HOSTNAME_LENGTH,), packet, offset, hostname)
offset += struct.calcsize('!%ds' % (MAX_HOSTNAME_LENGTH,))
# next, pad & pack the service description
service = service + '\0'
if len(service) < MAX_DESCRIPTION_LENGTH:
service += get_random_alphanumeric_bytes(MAX_DESCRIPTION_LENGTH - len(service))
struct.pack_into('%ds' % (MAX_DESCRIPTION_LENGTH,), packet, offset, service)
offset += struct.calcsize('!%ds' % (MAX_DESCRIPTION_LENGTH))
# finally, pad & pack the plugin output
output = output + '\0'
if len(output) < MAX_PLUGINOUTPUT_LENGTH:
output += get_random_alphanumeric_bytes(MAX_PLUGINOUTPUT_LENGTH - len(output))
struct.pack_into('%ds' % (MAX_PLUGINOUTPUT_LENGTH,), packet, offset, output)
# compute the CRC32 of what we have so far
crc_val = binascii.crc32(packet) & 0xffffffffL
struct.pack_into('!L', packet, 4, crc_val)
return packet.tostring()
示例8: comms_on
def comms_on():
sock = Udpsocket([])
data = ctypes.create_string_buffer(13)
data[0:9] = 'RF SW CMD'
struct.pack_into("<I", data, 9, settings.RF_SW_CMD_ON_INT)
d = bytearray(data)
sock.sendto(d, (packet_settings.FRAME_RECEIVER_IP, packet_settings.FRAME_RECEIVER_PORT))
示例9: pdpte_create_binary_file
def pdpte_create_binary_file(self):
# pae needs a pdpte at 32byte aligned address
# Even though we have only 4 entries in the pdpte we need to move
# the self.output_offset variable to the next page to start pushing
# the pd contents
#
# FIXME: This wastes a ton of RAM!!
if args.verbose:
print("PDPTE at 0x%x" % self.pd_start_addr)
for pdpte in range(self.total_pages + 1):
if pdpte in self.get_pdpte_list():
present = 1 << 0
addr_of_pd = (((self.pd_start_addr + 4096) +
self.get_pdpte_list().index(pdpte) *
4096) >> 12) << 12
binary_value = (present | addr_of_pd)
else:
binary_value = 0
struct.pack_into(page_entry_format,
self.output_buffer,
self.output_offset,
binary_value)
self.output_offset += struct.calcsize(page_entry_format)
示例10: scan_rays
def scan_rays(rays, max_distance, ray_origins=False, keep_render_setup=False, do_shading=True):
elementsPerRay = 3
if ray_origins == True:
elementsPerRay = 6
numberOfRays = int(len(rays)/elementsPerRay)
rays_buffer = (ctypes.c_float * numberOfRays*elementsPerRay)()
struct.pack_into("%df"%(numberOfRays*elementsPerRay), rays_buffer, 0, *rays[:numberOfRays*elementsPerRay])
returns_buffer = (ctypes.c_float * (numberOfRays * ELEMENTS_PER_RETURN))()
print ("Raycount: ", numberOfRays)
returns_buffer_uint = ctypes.cast(returns_buffer, ctypes.POINTER(ctypes.c_uint))
array_of_returns = []
try:
bpy.ops.render.blensor(raycount = numberOfRays,maximum_distance = max_distance, vector_strptr="%016X"%(ctypes.addressof(rays_buffer)), return_vector_strptr="%016X"%(ctypes.addressof(returns_buffer)), elements_per_ray = elementsPerRay, keep_render_setup=keep_render_setup,
shading = do_shading)
for idx in range(numberOfRays):
if returns_buffer[idx*ELEMENTS_PER_RETURN] < max_distance and returns_buffer[idx*ELEMENTS_PER_RETURN]>0.0 :
#The ray may have been reflecten and refracted. But the laser
#does not know that so we need to calculate the point which
#is the measured distance away from the sensor but without
#beeing reflected/refracted. We use the original ray direction
vec = [float(rays[idx*elementsPerRay]),
float(rays[idx*elementsPerRay+1]),
float(rays[idx*elementsPerRay+2])]
veclen = math.sqrt(vec[0]**2+vec[1]**2+vec[2]**2)
raydistance = float(returns_buffer[idx*ELEMENTS_PER_RETURN])
vec[0] = raydistance * vec[0]/veclen
vec[1] = raydistance * vec[1]/veclen
vec[2] = raydistance * vec[2]/veclen
ret = [ float(returns_buffer[e + idx*ELEMENTS_PER_RETURN]) for e in range(4) ]
ret[1] = vec[0]
ret[2] = vec[1]
ret[3] = vec[2]
ret.append(returns_buffer_uint[idx*ELEMENTS_PER_RETURN+4]) #objectid
ret.append((returns_buffer[idx*ELEMENTS_PER_RETURN+5],
returns_buffer[idx*ELEMENTS_PER_RETURN+6],
returns_buffer[idx*ELEMENTS_PER_RETURN+7])) # RGB Value of the material
ret.append(idx) # Store the index per return as the last element
array_of_returns.append(ret)
except TypeError as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_tb(exc_traceback)
finally:
del rays_buffer
del returns_buffer
return array_of_returns
示例11: initial_connection
async def initial_connection(self, data):
state = self._connection
state.ssrc = data['ssrc']
state.voice_port = data['port']
packet = bytearray(70)
struct.pack_into('>I', packet, 0, state.ssrc)
state.socket.sendto(packet, (state.endpoint_ip, state.voice_port))
recv = await self.loop.sock_recv(state.socket, 70)
log.debug('received packet in initial_connection: %s', recv)
# the ip is ascii starting at the 4th byte and ending at the first null
ip_start = 4
ip_end = recv.index(0, ip_start)
state.ip = recv[ip_start:ip_end].decode('ascii')
# the port is a little endian unsigned short in the last two bytes
# yes, this is different endianness from everything else
state.port = struct.unpack_from('<H', recv, len(recv) - 2)[0]
log.debug('detected ip: %s port: %s', state.ip, state.port)
# there *should* always be at least one supported mode (xsalsa20_poly1305)
modes = [mode for mode in data['modes'] if mode in self._connection.supported_modes]
log.debug('received supported encryption modes: %s', ", ".join(modes))
mode = modes[0]
await self.select_protocol(state.ip, state.port, mode)
log.info('selected the voice protocol for use (%s)', mode)
await self.client_connect()
示例12: throttle
def throttle(self,speed,direction):
'''
This method controls the train's throttle.
The two parameters are:
speed 0 - 127 where 0 = stop
direction 0 - FORWARD
1 - REVERSE
For imformation about the message sent by this method refer to the XpressNet protocol:
'Locomotive speed and direction operations'
example:
t1.throttle(15,FORWARD) # move train forward with a speed of 15 steps
t1.throttle(0,FORWARD) # stop train
'''
message = bytearray('E400000000'.decode('hex'))
message[1] = 0x13 #128 speed steps
struct.pack_into(">H",message,2,self.address)
# NB If speed is set to max, the command has to be done differently
# else the elink bombs, so it is just easier to block it.
if speed > 120:
speed = 120
message[4] = speed
if direction == FORWARD : message[4] |= 0x80
elif direction == REVERSE : message[4] &= 0x7F
parity(message)
send (message)
示例13: icmpv6_csum
def icmpv6_csum(prev, buf):
ph = struct.pack('!16s16sBBH', prev.src, prev.dst, 0, prev.nxt,
prev.payload_length)
h = bytearray(buf)
struct.pack_into('!H', h, 2, 0)
return socket.htons(packet_utils.checksum(ph + h))
示例14: set
def set(self, value):
"""
If a primitive, assigns data.
Complex objects should raise a ValueError.
"""
struct.pack_into(self.pack, self.buf, self.offset, value)
示例15: test3
def test3():
class X(object):
def __init__(self, a,b):
self.a, self.b = a,b # ubyte, float
def __eq__(self, other):
return self.a == other.a and abs(self.b - other.b) < 1e-6
x = [ X(1, .1), X(2, .2) ]
fmt = "=Bf"
x_bytes = struct.calcsize(fmt)
assert( x_bytes == 5 )
buf = bytearray( len(x) * x_bytes )
for i,n in enumerate(x):
struct.pack_into( fmt, buf, i*x_bytes, n.a, n.b )
back = []
count = int( len(buf) / x_bytes )
for i in range(count):
ab = struct.unpack_from( fmt, buf, i*x_bytes )
back += [ X(*ab) ]
assert( back == x )