Converting decimal to base is just one of the base conversion problems. In Python programming, there are two main ways to complete the base conversion:Custom coded implementations and invocation of library functions
Custom encoding implementation refers to writing a functional method in python according to the mathematical principles of base conversion.
To call library functions, you can use the out-of-the-box functions that come with the Python language, or use the out-of-the-box functions provided by third-party developers.
The mathematical principle of decimal to binary
To implement decimal to binary conversion with custom encoding, you must first understand the mathematics of the base conversion. In line with the principle of focusing on Python ** programming itself, please refer to the mathematical principle of decimal to binary: How to convert decimal to binary.
2. Writing**
The implementation idea is as follows:
Customize a function with parameters, and there is no restriction on the type of arguments.
Validly determine whether the input parameter is integer data or floating-point data, and output an error message for invalid data and return empty content.
It is processed separately depending on whether the parameter is integer data or floating-point data.
The details are as follows:
def decimal_to_binary(decimal):Debug:binary = ""
if isinstance(decimal, int):
while decimal > 0:
remainder = decimal % 2
binary = str(remainder) +binary
decimal //= 2
elif isinstance(decimal, float):
num1 = int(math.modf(decimal)[1])
num2 = math.modf(decimal)[0]
while num1 > 0:
rem1 = num1 % 2
binary = str(rem1) +binary
num1 //= 2
binary = binary + "."
while math.modf(num2)[0] != 0.0:
rema2 = num2 * 2
temp_num = int(math.modf(rema2)[1])
binary = binary + str(temp_num)
num2 = math.modf(num2 * 2)[0]
else:print("error!!!")
return
return "0b" + binary
if __name__ == '__main__':The output result is as follows:print(decimal_to_binary(12))
print(decimal_to_binary(12.625))
This section mainly introduces the call to the official library functions of Python to implement decimal to binary. The built-in functions of the Python language provide bin(), int(), oct(), and hex(), and the target base system corresponds to binary, decimal, octal, and hexadecimal respectively.
The purpose of this article is to provide a reference for a decimal number to binary number solution, so the use of the bin() function is emphasized.
The official statement for the bin() function is as follows:
As can be clearly seen from the declaration information in the figure above, the data type of the bin() parameter is restricted to the int type, so you need to pay attention to the parameter passing. When a decimal integer is implemented with the bin() function, you only need to pass in the int type to get the result. For decimal numbers with decimals, bin() is not suitable.