如何将float decimal转换为float octal / binary?

时间:2016-10-14 05:12:46

标签: python binary floating-point octal

我到处搜索,找到将float转换为八进制或二进制的方法。我知道float.hexfloat.fromhex。这是一个可以为八进制/二进制值做同样工作的模块吗?

例如:我有一个浮动12.325,我应该得到浮动八进制14.246。告诉我,我怎么能这样做?提前谢谢。

2 个答案:

答案 0 :(得分:1)

你可以写自己的,如果你只关心三个小数位,那么将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

答案 1 :(得分:0)

以下是解决方案,解释如下:

def ToLessThanOne(num): # Change "num" into a decimal <1
    while num > 1:
        num /= 10
    return num

def FloatToOctal(flo, places=8): # Flo is float, places is octal places
    main, dec = str(flo).split(".") # Split into Main (integer component)
                                    # and Dec (decimal component)
    main, dec = int(main), int(dec) # Turn into integers

    res = oct(main)[2::]+"." # Turn the integer component into an octal value
                             # while removing the "ox" that would normally appear ([2::])
                             # Also, res means result

    # NOTE: main and dec are being recycled here

    for x in range(places): 
        main, dec = str((ToLessThanOne(dec))*8).split(".") # main is integer octal
                                                           # component
                                                           # dec is octal point
                                                           # component
        dec = int(dec) # make dec an integer

        res += main # Add the octal num to the end of the result

    return res # finally return the result

因此,您可以执行print(FloatToOctal(12.325))并打印出14.246314631

最后,如果你想要更少的八进制位数(小数位但是八进制),只需添加places参数:print(FloatToOctal(12.325, 3)),根据这个网站正确返回14.246:{{ 3}}