Python 沒有提供任何內置方法來輕鬆地將浮點十進製數轉換為二進製數。所以,讓我們手動執行此操作。
方法:
要將浮點十進製數轉換為二進製,首先將整數部分轉換為二進製形式,然後將小數部分轉換為二進製形式,最後將兩個結果組合得到最終答案。
對於整數部分,繼續將數字除以 2 並記下餘數,除非被除數小於 2。如果是這樣,停止並將所有餘數複製在一起。
對於小數部分,繼續將小數部分乘以 2,直到並且除非 0 作為小數部分留下。第一次相乘後,記下整數部分,然後再次將新值的小數部分乘以 2。繼續這樣做,直到達到完美數字。
Above steps can be written as:
1(base 10) = 1(base 2) and .234(base 10) = .0011(base 2)Now, to get the binary of 1.234, merge both results as a complete number.
(1)10 = (1)2
[approx.]
(.234)10 = (.0011)2
(1.234)10 = (1.0011...)2
(1.234)10 = (1.0011)2
下麵是實現:
Python3
# Python program to convert float
# decimal to binary number
# Function returns octal representation
def float_bin(number, places = 3):
# split() separates whole number and decimal
# part and stores it in two separate variables
whole, dec = str(number).split(".")
# Convert both whole number and decimal
# part from string type to integer type
whole = int(whole)
dec = int (dec)
# Convert the whole number part to it's
# respective binary form and remove the
# "0b" from it.
res = bin(whole).lstrip("0b") + "."
# Iterate the number of times, we want
# the number of decimal places to be
for x in range(places):
# Multiply the decimal value by 2
# and separate the whole number part
# and decimal part
whole, dec = str((decimal_converter(dec)) * 2).split(".")
# Convert the decimal part
# to integer again
dec = int(dec)
# Keep adding the integer parts
# receive to the result variable
res += whole
return res
# Function converts the value passed as
# parameter to it's decimal representation
def decimal_converter(num):
while num > 1:
num /= 10
return num
# Driver Code
# Take the user input for
# the floating point number
n = input("Enter your floating point value:\n")
# Take user input for the number of
# decimal places user want result as
p = int(input("Enter the number of decimal places of the result:\n"))
print(float_bin(n, places = p))
輸出:
Enter your floating point value: 1.234 Enter the number of decimal places of the result: 4 1.0011
Enter your floating point value: 11.234 Enter the number of decimal places of the result: 4 1011.0011
相關用法
- Python binary轉ASCII用法及代碼示例
- Python ASCII轉Binary用法及代碼示例
- Python Binary轉Hexadecimal用法及代碼示例
- Python String轉Binary用法及代碼示例
- Python binary轉string用法及代碼示例
- Python image轉binary用法及代碼示例
注:本文由純淨天空篩選整理自retr0大神的英文原創作品 Python program to convert floating to binary。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。