簡體   English   中英

如何將浮點十進制轉換為浮點八進制/二進制?

[英]How do I convert float decimal to float octal/binary?

我到處搜索以找到將浮點數轉換為八進制或二進制的方法。 我知道float.hexfloat.fromhex 是否有一個模塊可以對八進制/二進制值做同樣的工作?

例如:我有一個浮點數12.325 ,我應該得到浮點數八進制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

這是解決方案,解釋如下:

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 ,根據本網站是正確的: http : 14.246 /

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM