• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python struct.calcsize函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中struct.calcsize函数的典型用法代码示例。如果您正苦于以下问题:Python calcsize函数的具体用法?Python calcsize怎么用?Python calcsize使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了calcsize函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:jaseg,项目名称:cerebrum,代码行数:26,代码来源:ganglion.py


示例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}))
开发者ID:mcworden,项目名称:mi-dataset-1,代码行数:28,代码来源:adcpt_m_wvs.py


示例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})
开发者ID:mcworden,项目名称:mi-dataset-1,代码行数:27,代码来源:adcpt_m_wvs.py


示例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()
开发者ID:tstellanova,项目名称:piksi_firmware,代码行数:34,代码来源:observation_view.py


示例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
开发者ID:1tylermitchell,项目名称:pym,代码行数:30,代码来源:membaseclient.py


示例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
开发者ID:mit-uav,项目名称:pixhawk,代码行数:32,代码来源:_UavEstState.py


示例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)
开发者ID:leyyer,项目名称:exfsh,代码行数:27,代码来源:extfs.py


示例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
开发者ID:WeirdCoder,项目名称:rss-2014-team-3,代码行数:35,代码来源:_GUIPolyMsg.py


示例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
开发者ID:WeirdCoder,项目名称:rss-2014-team-3,代码行数:34,代码来源:_GUIPolyMsg.py


示例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
开发者ID:bioinroboticsuottawa,项目名称:dextrus_ws,代码行数:60,代码来源:_spatial_params.py


示例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)
开发者ID:Aha00a,项目名称:play1,代码行数:29,代码来源:win32gui_struct.py


示例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
开发者ID:rbian,项目名称:avocado-vt,代码行数:29,代码来源:VirtIoChannel_guest_send_receive.py


示例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
开发者ID:greenthrall,项目名称:BB_Sync_Test,代码行数:28,代码来源:BodyBugg.py


示例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)
开发者ID:greenthrall,项目名称:BB_Sync_Test,代码行数:25,代码来源:BodyBugg.py


示例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
开发者ID:dtbinh,项目名称:vrep_ros,代码行数:33,代码来源:_simRosSetJointState.py


示例16: 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
     (self.result,) = _struct_i.unpack(str[start:end])
     start = end
     end += 4
     (length,) = _struct_I.unpack(str[start:end])
     pattern = '<%si'%length
     start = end
     end += struct.calcsize(pattern)
     self.resolution = 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.buffer = struct.unpack(pattern, str[start:end])
     return self
   except struct.error as e:
     raise genpy.DeserializationError(e) #most likely buffer underfill
开发者ID:AndrewChubatiuk,项目名称:ROS-UAV,代码行数:27,代码来源:_simRosGetVisionSensorDepthBuffer.py


示例17: 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.workspace_region_shape is None:
       self.workspace_region_shape = arm_navigation_msgs.msg.Shape()
     if self.workspace_region_pose is None:
       self.workspace_region_pose = geometry_msgs.msg.PoseStamped()
     end = 0
     start = end
     end += 1
     (self.workspace_region_shape.type,) = _struct_b.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.workspace_region_shape.dimensions = numpy.frombuffer(str[start:end], dtype=numpy.float64, count=length)
     start = end
     end += 4
     (length,) = _struct_I.unpack(str[start:end])
     pattern = '<%si'%length
     start = end
     end += struct.calcsize(pattern)
     self.workspace_region_shape.triangles = numpy.frombuffer(str[start:end], dtype=numpy.int32, count=length)
     start = end
     end += 4
     (length,) = _struct_I.unpack(str[start:end])
     self.workspace_region_shape.vertices = []
     for i in range(0, length):
       val1 = geometry_msgs.msg.Point()
       _x = val1
       start = end
       end += 24
       (_x.x, _x.y, _x.z,) = _struct_3d.unpack(str[start:end])
       self.workspace_region_shape.vertices.append(val1)
     _x = self
     start = end
     end += 12
     (_x.workspace_region_pose.header.seq, _x.workspace_region_pose.header.stamp.secs, _x.workspace_region_pose.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.workspace_region_pose.header.frame_id = str[start:end].decode('utf-8')
     else:
       self.workspace_region_pose.header.frame_id = str[start:end]
     _x = self
     start = end
     end += 56
     (_x.workspace_region_pose.pose.position.x, _x.workspace_region_pose.pose.position.y, _x.workspace_region_pose.pose.position.z, _x.workspace_region_pose.pose.orientation.x, _x.workspace_region_pose.pose.orientation.y, _x.workspace_region_pose.pose.orientation.z, _x.workspace_region_pose.pose.orientation.w,) = _struct_7d.unpack(str[start:end])
     return self
   except struct.error as e:
     raise genpy.DeserializationError(e) #most likely buffer underfill
开发者ID:shivamvats,项目名称:pr2_planning,代码行数:60,代码来源:_WorkspaceParameters.py


示例18: _unpack

  def _unpack(self, data):
    """ Unpack the data blob as a motoboot image and return the list
    of contained image objects"""
    num_imgs_fmt = "<L"
    num_imgs_size = struct.calcsize(num_imgs_fmt)
    num_imgs, = struct.unpack(num_imgs_fmt, data[:num_imgs_size])

    img_info_format = "<24sLL"
    img_info_size = struct.calcsize(img_info_format)

    imgs = [ struct.unpack(img_info_format, data[num_imgs_size + i*img_info_size:num_imgs_size + (i+1)*img_info_size]) for i in range(num_imgs) ]

    magic_format = "<8s"
    magic_size = struct.calcsize(magic_format)
    magic, = struct.unpack(magic_format, data[num_imgs_size + NUM_MAX_IMAGES*img_info_size:num_imgs_size + NUM_MAX_IMAGES*img_info_size + magic_size])
    if magic != MAGIC:
      raise BadMagicError

    img_objs = []
    for name, start, end in imgs:
      start_offset = HEADER_SIZE + start * SECTOR_SIZE
      end_offset = HEADER_SIZE + (end + 1) * SECTOR_SIZE - 1
      img = common.File(trunc_to_null(name), data[start_offset:end_offset+1])
      img_objs.append(img)

    self.unpacked_images = img_objs
开发者ID:CleanWhale,项目名称:android_device_moto_shamu,代码行数:26,代码来源:releasetools.py


示例19: 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.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 = 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.covariance = struct.unpack(pattern, str[start:end])
     self.timestamp.canon()
     return self
   except struct.error as e:
     raise genpy.DeserializationError(e) #most likely buffer underfill
开发者ID:mit-uav,项目名称:pixhawk,代码行数:31,代码来源:_UavEstState.py


示例20: load_mnist

def load_mnist(im_path, lb_path):
	# loading images
	binfile = open(im_path, 'rb')
	buf = binfile.read()
	index = 0
	magic,numImages,numRows,numColumns = \
		struct.unpack_from('>IIII' , buf , index)
	index += struct.calcsize('>IIII')
	if magic!=2051:
		raise NameError('MNIST TRAIN-IMAGE INCCORECT!')
	ims = np.zeros([numImages, numRows*numColumns])
	for i in range(numImages):
		ims[i,:] = struct.unpack_from('>784B', buf, index)
		index += struct.calcsize('>784B');
	# loading labels
	binfile = open(lb_path, 'rb')
	buf = binfile.read()
	index = 0
	magic,numLabels = struct.unpack_from(
		'>II', 
		buf, 
		index
	)
	index += struct.calcsize('>II')
	if magic!=2049:
		raise NameError('MNIST TRAIN-LABEL INCORRECT!')
	lbs = np.zeros(numLabels)
	lbs[:] = struct.unpack_from(
		'>'+ str(numLabels) +'B', 
		buf, 
		index
	)
	return [ims, numRows, numColumns, lbs]
开发者ID:xiangchao027,项目名称:hybrid-learning-neural-network,代码行数:33,代码来源:main.py



注:本文中的struct.calcsize函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python struct.error函数代码示例发布时间:2022-05-27
下一篇:
Python struct._unpack函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap