在Python 2.7中,如何将浮点十进制(从十进制模块)转换为二进制表示(字节序列,我可以记录到二进制文件并回读)?我对最小可能的二进制表示感兴趣。提前谢谢!
答案 0 :(得分:3)
也许是这样的?就个人而言,我用ASCII编写数据 - 用二进制编写通常是不值得的。
#!/usr/local/cpython-2.7/bin/python
import pickle as pickle_mod
import decimal as decimal_mod
decimal = decimal_mod.Decimal(str(1.0 / 9.0))
pickled = pickle_mod.dumps(decimal)
#print repr(pickled)
with open('decimal.bin', 'wb') as file_:
file_.write(pickled)
with open('decimal.bin', 'rb') as file_:
data = file_.read()
decimal2 = pickle_mod.loads(data)
print decimal2
答案 1 :(得分:0)
my_float = Decimal("1.23")
with open("some_file.bin","w") as f:
f.write("%s"%my_float.to_eng_string()) #string is a series of bytes
print Decimal(open("some_file.bin").read()) #decoded bytes back to Decimal
这主要是Decimal的内部表示是
的方式结构将是三个元素的元组:符号,数字和指数。符号为1或0,数字是十进制数字的元组,指数是带符号的int或long
十进制((1,(3,2,2,5), - 2))# - -32.25