本文整理汇总了Python中struct.calcsize函数的典型用法代码示例。如果您正苦于以下问题:Python calcsize函数的具体用法?Python calcsize怎么用?Python calcsize使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了calcsize函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _callfunc
def _callfunc(self, fid, argsfmt, args, retfmt):
"""Call a function on the device by id, directly passing argument/return format parameters."""
# Make a list out of the arguments if they are none
#print('calling function No. {}, args({}) {}, returning {}'.format(fid, argsfmt, args, retfmt))
if not (isinstance(args, tuple) or isinstance(args, list)):
args = [args]
with self._ser as s:
# Send the encoded data
cmd = b'\\#' + escape(struct.pack(">HHH", self.node_id, fid, struct.calcsize(argsfmt)) + struct.pack(argsfmt, *args))
s.write(cmd)
# payload length
(clen,) = struct.unpack(">H", s.read(2))
# payload data
cbytes = s.read(clen)
if clen != struct.calcsize(retfmt):
# CAUTION! This error is thrown not because the user supplied a wrong value but because the device answered in an unexpected manner.
# FIXME raise an error here or let the whole operation just fail in the following struct.unpack?
raise AttributeError("Device response format problem: Length mismatch: {} != {}".format(clen, struct.calcsize(retfmt)))
rv = struct.unpack(retfmt, cbytes)
# Try to interpret the return value in a useful manner
if len(rv) == 0:
return None
elif len(rv) == 1:
return rv[0]
else:
return list(rv)
示例2: _parse_directional_spectrum
def _parse_directional_spectrum(self, offset, rules):
"""
Convert the binary data into particle data for the Directional Spectrum Data Type
"""
# Unpack the unpacking rules
(num_freq_name, num_dir_name, good_name, dat_name),\
(num_freq_fmt, num_dir_fmt, good_fmt, dat_fmt) = zip(*rules)
# First unpack the array lengths and single length values
(num_freq_data, num_dir_data, dspec_good_data) = struct.unpack_from(
'<%s%s%s' % (num_freq_fmt, num_dir_fmt, good_fmt), self.raw_data, offset)
# Then unpack the array using the retrieved lengths values
next_offset = offset + struct.calcsize(num_freq_fmt) + struct.calcsize(num_dir_fmt) + \
struct.calcsize(good_fmt)
dspec_dat_list_data = struct.unpack_from(
'<%s%s' % (num_freq_data * num_dir_data, dat_fmt), self.raw_data, next_offset)
# convert to numpy array and reshape the data per IDD spec
transformed_dat_data = numpy.array(dspec_dat_list_data).reshape(
(num_freq_data, num_dir_data)).tolist()
# Add to the collected parameter data
self.final_result.extend(
({DataParticleKey.VALUE_ID: num_freq_name, DataParticleKey.VALUE: num_freq_data},
{DataParticleKey.VALUE_ID: num_dir_name, DataParticleKey.VALUE: num_dir_data},
{DataParticleKey.VALUE_ID: good_name, DataParticleKey.VALUE: dspec_good_data},
{DataParticleKey.VALUE_ID: dat_name, DataParticleKey.VALUE: transformed_dat_data}))
示例3: _parse_values
def _parse_values(self, offset, rules):
"""
Convert the binary data into particle data for the given rules
"""
position = offset
# Iterate through the unpacking rules and append the retrieved values with its corresponding
# particle name
for key, formatter in rules:
# Skip over spare values
if AdcptMWVSParticleKey.SPARE in key:
position += struct.calcsize(formatter)
continue
value = list(struct.unpack_from('<%s' % formatter, self.raw_data, position))
# Support unpacking single values and lists
if len(value) == 1:
value = value[0]
if AdcptMWVSParticleKey.START_TIME in key:
timestamp = ((value[0]*100 + value[1]), value[2], value[3], value[4],
value[5], value[6], value[7], 0, 0)
log.trace("TIMESTAMP: %s", timestamp)
elapsed_seconds = calendar.timegm(timestamp)
self.set_internal_timestamp(unix_time=elapsed_seconds)
log.trace("DATA: %s:%s @ %s", key, value, position)
position += struct.calcsize(formatter)
self.final_result.append({DataParticleKey.VALUE_ID: key,
DataParticleKey.VALUE: value})
示例4: old_obs_callback
def old_obs_callback(self, data, sender=None):
print "Received deprecated observation messages. Please update your Piksi."
if (sender is not None and
(self.relay ^ (sender == 0))):
return
hdr_fmt = "<dH"
hdr_size = struct.calcsize(hdr_fmt)
tow, wn = struct.unpack("<dH", data[:hdr_size])
self.gps_tow = tow
self.gps_week = wn
self.t = datetime.datetime(1980, 1, 6) + \
datetime.timedelta(weeks=self.gps_week) + \
datetime.timedelta(seconds=self.gps_tow)
# Observation message format
# double P; /**< Pseudorange (m) */
# double L; /**< Carrier-phase (cycles) */
# float snr; /**< Signal-to-Noise ratio */
# u8 prn; /**< Satellite number. */
obs_fmt = '<ddfB'
obs_size = struct.calcsize(obs_fmt)
n_obs = (len(data) - hdr_size) / obs_size
obs_data = data[hdr_size:]
self.obs = {}
for i in range(n_obs):
P, L, snr, prn = struct.unpack(obs_fmt, obs_data[:obs_size])
obs_data = obs_data[obs_size:]
self.obs[prn] = (P, L, snr)
self.update_obs()
self.rinex_save()
示例5: _parse_sync_response
def _parse_sync_response(self, data):
keyspecs = []
nkeys = struct.unpack(">H", data[0: struct.calcsize("H")])[0]
offset = struct.calcsize("H")
for i in xrange(nkeys):
spec = {}
width = struct.calcsize("QHHB")
spec['cas'], spec['vbucket'], keylen, eventid = struct.unpack(">QHHB", data[offset: offset + width])
offset += width
spec['key'] = data[offset: offset + keylen]
offset += keylen
if eventid == MemcachedConstants.CMD_SYNC_EVENT_PERSISTED:
spec['event'] = 'persisted'
elif eventid == MemcachedConstants.CMD_SYNC_EVENT_MODIFED:
spec['event'] = 'modified'
elif eventid == MemcachedConstants.CMD_SYNC_EVENT_DELETED:
spec['event'] = 'deleted'
elif eventid == MemcachedConstants.CMD_SYNC_EVENT_REPLICATED:
spec['event'] = 'replicated'
elif eventid == MemcachedConstants.CMD_SYNC_INVALID_KEY:
spec['event'] = 'invalid key'
elif spec['event'] == MemcachedConstants.CMD_SYNC_INVALID_CAS:
spec['event'] = 'invalid cas'
else:
spec['event'] = eventid
keyspecs.append(spec)
return keyspecs
示例6: deserialize_numpy
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
try:
if self.timestamp is None:
self.timestamp = genpy.Time()
end = 0
_x = self
start = end
end += 8
(_x.timestamp.secs, _x.timestamp.nsecs,) = _struct_2I.unpack(str[start:end])
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
pattern = '<%sd'%length
start = end
end += struct.calcsize(pattern)
self.state = numpy.frombuffer(str[start:end], dtype=numpy.float64, count=length)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
pattern = '<%sd'%length
start = end
end += struct.calcsize(pattern)
self.covariance = numpy.frombuffer(str[start:end], dtype=numpy.float64, count=length)
self.timestamp.canon()
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
示例7: __init__
def __init__(self, idx, buf):
self.inode_no = idx
sb = buffer(bytearray(buf))
sz = 0
fmt = "<2H5I2H3I"
(self.i_mode,
self.i_uid,
self.i_size,
self.i_atime,
self.i_ctime,
self.i_mtime,
self.i_dtime,
self.i_gid,
self.i_links_count,
self.i_blocks,
self.i_flags,
self.i_osd1) = struct.unpack_from(fmt, sb, sz)
sz += struct.calcsize(fmt)
fmt = "<15I"
self.i_block = struct.unpack_from(fmt, sb, sz)
sz += struct.calcsize(fmt)
fmt = "<4I12s"
(self.i_gneration,
self.i_file_acl,
self.i_dir_acl,
self.i_faddr,
self.i_osd2) = struct.unpack_from(fmt, sb, sz)
示例8: deserialize_numpy
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
try:
if self.c is None:
self.c = lab5_msgs.msg.ColorMsg()
end = 0
_x = self
start = end
end += 28
(_x.c.r, _x.c.g, _x.c.b, _x.numVertices) = _struct_3qi.unpack(str[start:end])
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
pattern = "<%sf" % length
start = end
end += struct.calcsize(pattern)
self.x = numpy.frombuffer(str[start:end], dtype=numpy.float32, count=length)
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
pattern = "<%sf" % length
start = end
end += struct.calcsize(pattern)
self.y = numpy.frombuffer(str[start:end], dtype=numpy.float32, count=length)
_x = self
start = end
end += 8
(_x.closed, _x.filled) = _struct_2i.unpack(str[start:end])
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
示例9: deserialize
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
try:
if self.c is None:
self.c = lab5_msgs.msg.ColorMsg()
end = 0
_x = self
start = end
end += 28
(_x.c.r, _x.c.g, _x.c.b, _x.numVertices) = _struct_3qi.unpack(str[start:end])
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
pattern = "<%sf" % length
start = end
end += struct.calcsize(pattern)
self.x = struct.unpack(pattern, str[start:end])
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
pattern = "<%sf" % length
start = end
end += struct.calcsize(pattern)
self.y = struct.unpack(pattern, str[start:end])
_x = self
start = end
end += 8
(_x.closed, _x.filled) = _struct_2i.unpack(str[start:end])
return self
except struct.error as e:
raise genpy.DeserializationError(e) # most likely buffer underfill
示例10: deserialize
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
try:
if self.header is None:
self.header = std_msgs.msg.Header()
end = 0
_x = self
start = end
end += 12
(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs,) = _struct_3I.unpack(str[start:end])
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.header.frame_id = str[start:end].decode('utf-8')
else:
self.header.frame_id = str[start:end]
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
pattern = '<%sd'%length
start = end
end += struct.calcsize(pattern)
self.acceleration = struct.unpack(pattern, str[start:end])
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
pattern = '<%sd'%length
start = end
end += struct.calcsize(pattern)
self.orientation = struct.unpack(pattern, str[start:end])
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
pattern = '<%sd'%length
start = end
end += struct.calcsize(pattern)
self.angular = struct.unpack(pattern, str[start:end])
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
pattern = '<%sd'%length
start = end
end += struct.calcsize(pattern)
self.magnetic = struct.unpack(pattern, str[start:end])
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
pattern = '<%sd'%length
start = end
end += struct.calcsize(pattern)
self.timestamp = struct.unpack(pattern, str[start:end])
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
示例11: UnpackDEV_BROADCAST
def UnpackDEV_BROADCAST(lparam):
# guard for 0 here, otherwise PyMakeBuffer will create a new buffer.
if lparam == 0:
return None
hdr_size = struct.calcsize("iii")
hdr_buf = win32gui.PyMakeBuffer(hdr_size, lparam)
size, devtype, reserved = struct.unpack("iii", hdr_buf)
rest = win32gui.PyMakeBuffer(size-hdr_size, lparam+hdr_size)
extra = x = {}
if devtype == win32con.DBT_DEVTYP_HANDLE:
# 2 handles, a GUID, a LONG and possibly an array following...
fmt = "PP16sl"
x['handle'], x['hdevnotify'], guid_bytes, x['nameoffset'] = \
struct.unpack(fmt, rest[:struct.calcsize(fmt)])
x['eventguid'] = pywintypes.IID(guid_bytes, True)
elif devtype == win32con.DBT_DEVTYP_DEVICEINTERFACE:
# guid, null-terminated name
x['classguid'] = pywintypes.IID(rest[:16], 1)
name = rest[16:]
if '\0' in name:
name = name.split('\0', 1)[0]
x['name'] = name
elif devtype == win32con.DBT_DEVTYP_VOLUME:
# int mask and flags
x['unitmask'], x['flags'] = struct.unpack("II", rest[:struct.calcsize("II")])
else:
raise NotImplementedError("unknown device type %d" % (devtype,))
return DEV_BROADCAST_INFO(devtype, **extra)
示例12: shake_hand
def shake_hand(self, size=0, action="receive"):
hi_msg_len = struct.calcsize(self.hi_format)
ack_msg_len = struct.calcsize(self.ack_format)
if action == "send":
self.send(self.hi_msg)
txt = self.receive(hi_msg_len)
out = struct.unpack(self.hi_format, txt)[0]
if out != "HI":
raise ShakeHandError("Fail to get HI from guest.")
size_s = struct.pack("q", size)
self.send(size_s)
txt = self.receive(ack_msg_len)
ack_str = struct.unpack(self.ack_format, txt)[0]
if ack_str != self.ack_msg:
raise "Guest did not ACK the file size message."
return size
elif action == "receive":
txt = self.receive(hi_msg_len)
hi_str = struct.unpack(self.hi_format, txt)[0]
if hi_str != self.hi_msg:
raise ShakeHandError("Fail to get HI from guest.")
self.send(txt)
size = self.receive(8)
print("xxxx size = %s" % size)
if size:
size = struct.unpack("q", size)[0]
txt = struct.pack(self.ack_format, self.ack_msg)
self.send(txt)
return size
示例13: ReadRecord
def ReadRecord(d, offset=0x0):
id = d[0]
d=d[1:] # Eat id
if id == 0xff or id == 0x4: # Normal end of Data
return id, None, None
sztotal = 1
assert RecPack.has_key(id), "Unknown record ID %i at offset %i" % (id, offset)
if RecRepeat.has_key(id):
sz = struct.calcsize(RecPack[id])
init=struct.unpack_from(RecRepeat[id][1], d)
szinit=struct.calcsize(RecRepeat[id][1])
d=d[szinit:]
sztotal += szinit
res=[]
for i in range(0, RecRepeat[id][0]):
res.append(struct.unpack_from(RecPack[id], d))
d=d[sz:]
sztotal += sz
elif type(RecPack[id]) == str:
sz = struct.calcsize(RecPack[id])
res = struct.unpack_from(RecPack[id], d)
sztotal += sz
elif type(RecPack[id]) == int: # 12-bit field array
# A padding byte 0xFF may be present
sz = RecPack[id] - 1
res = ReadPacked12Bit(d[:sz])
sztotal += sz
return id, sztotal, res
示例14: PrintRecords
def PrintRecords(labels, s4, fmtHead, fmtTail="", printHex=True, printNorm=True):
fmt = fmtHead
szHead = struct.calcsize(fmtHead)
szTail = struct.calcsize(fmtTail)
printableHead = string.join([x for x in fmtHead if fmtmap.has_key(x)],"")
printableTail = string.join([x for x in fmtTail if fmtmap.has_key(x)],"")
if fmtTail != "":
gap = len(s4[0]) - (struct.calcsize(fmtHead) + struct.calcsize(fmtTail))
fmt = fmtHead + ("x"*gap) + fmtTail
labels = ["LINE"] + labels[:len(printableHead)] + labels[len(labels)-len(printableTail):]
PrintMultiLineLabels(labels,6)
sys.stdout.write(6*" ")
PrintByteLabels(fmt, len(s4))
for i in range(0, len(s4)):
if printNorm:
sys.stdout.write("%5i:%s\n" % (i, StructToString(s4[i], fmt, 6)))
if printHex:
sys.stdout.write("\33[0m")
sys.stdout.write(" %s\n" % (StructToString(s4[i], fmt, 6, color=False, hexonly=True)))
if not ((i+1) % 40) or (i == len(s4) - 1):
PrintMultiLineLabels(labels,6)
sys.stdout.write(6*" ")
PrintByteLabels(fmt, len(s4))
#HexPrintMod(s4[i][:szHead].tostring() + s4[i][len(s4[i]) - szTail:].tostring(), szHead + szTail)
PrintByteStats(s4, fmt)
示例15: deserialize
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
try:
end = 0
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
pattern = '<%si'%length
start = end
end += struct.calcsize(pattern)
self.handles = struct.unpack(pattern, str[start:end])
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.setModes = str[start:end].decode('utf-8')
else:
self.setModes = str[start:end]
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
pattern = '<%sf'%length
start = end
end += struct.calcsize(pattern)
self.values = struct.unpack(pattern, str[start:end])
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill