我需要将 python 值转换为字节数组,反之亦然。
例如:
- 整数 256 -> [1, 1] // 256 = 1 * 255 + 1
- 字符串 'ab' -> [97, 98] // 'a' -> 97, 'b' -> 98
- 浮点 1.23 -> [63, 157, 112, 164] // 1.23 为 4 字节表示
对于 java kryo可以用于此目的:byte[] serializedValue = kryoSerializer.writeObjectData(value);
给我 value 的序列化结果。
我试过泡菜,但我不能使用它,因为它消耗 6 个字节来存储一个整数对象。
import pickle
Foo = 256
picklestring = pickle.dumps(Foo)
print len(picklestring) # returns 6
对此有任何提示吗?
添加
# http://docs.python.org/2/library/struct.html
# http://stackoverflow.com/questions/16818463/python-encode-decoder-for-serialization-deserialization-javas-kyro-equivalence
# http://stackoverflow.com/questions/11624190/python-convert-string-to-byte-array
import struct
# >f for
def encode(value):
formatString = ""
if type(value) is float:
formatString = ">f"
elif type(value) is int:
formatString = ">i"
elif type(value) is str:
formatString = ">s"
else:
raise Exception("Wrong data input: only supports float/int/string")
packed = struct.pack(formatString, value)
result = []
for i in packed:
# i is a string
result.append(ord(i[0]))
return result