我到处搜索以找到将 float 转换为八进制或二进制的方法。我知道 float.hex 和 float.fromhex。是否有模块可以对八进制/二进制值执行相同的工作?
例如:我有一个 float 12.325,我应该得到八进制 float 14.246。告诉我,我该怎么做?提前致谢。
请您参考如下方法:
你可以自己写,如果你只关心小数点后三位,然后将 n 设置为 3:
def frac_to_oct(f, n=4):
# store the number before the decimal point
whole = int(f)
rem = (f - whole) * 8
int_ = int(rem)
rem = (rem - int_) * 8
octals = [str(int_)]
count = 1
# loop until 8 * rem gives you a whole num or n times
while rem and count < n:
count += 1
int_ = int(rem)
rem = (rem - int_) * 8
octals.append(str(int_))
return float("{:o}.{}".format(whole, "".join(octals)))
使用您的输入 12.325:
In [9]: frac_to_oct(12.325)
Out[9]: 14.2463
In [10]: frac_to_oct(121212.325, 4)
Out[10]: 354574.2463
In [11]: frac_to_oct(0.325, 4)
Out[11]: 0.2463
In [12]: frac_to_oct(2.1, 4)
Out[12]: 2.0631
In [13]: frac_to_oct(0)
Out[13]: 0.0
In [14]: frac_to_oct(33)
Out[14]: 41.0
