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
网友评论