Y19M4W3-numpy.ndarray简易打包法

def pack_ndarray(x):
    ss = struct.pack('<I{}I'.format(len(x.shape)), len(x.shape), *x.shape)
    dr = bytes(repr(x.dtype.descr), 'ascii')
    ds = struct.pack('<I{}s'.format(len(dr)), len(dr), dr)
    xr = x.tobytes()
    xs = struct.pack('<I{}s'.format(len(xr)), len(xr), xr)
    return ss + ds + xs

def unpack_ndarray(s):
    sl, s = struct.unpack('<I', s[:4])[0], s[4:]
    _shape, s = struct.unpack('<{}I'.format(sl), s[:4*sl]), s[4*sl:]
    dl, s = struct.unpack('<I', s[:4])[0], s[4:]
    _descr, s = struct.unpack('<{}s'.format(dl), s[:dl])[0], s[dl:]
    _descr = eval(str(_descr, 'ascii'))
    xl, s = struct.unpack('<I', s[:4])[0], s[4:]
    _x, s = struct.unpack('<{}s'.format(xl), s[:xl])[0], s[xl:]
    _x = np.frombuffer(_x, np.dtype(_descr)).reshape(_shape)
    return _x, s
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。