# 在Python中将十进制转换为二进制：一种快速简单的方法

## 在Python中使用递归解决方案将十进制转换为二进制

``````#Recursive Function to convert Decimal to Binary

def decimalToBinary(ip_val):
if ip_val >= 1:
# recursive function call
decimalToBinary(ip_val // 2)

# printing remainder from each function call
print(ip_val % 2, end = '')

# Driver Code
if __name__ == '__main__':
# decimal value
ip_val = 24

# Calling special function
decimalToBinary(ip_val)
``````

``````011000
``````

## 使用内置函数在 Python 中将十进制转换为二进制

``````# Function to convert decimal to binary
# using built-in python function
def decimalToBinary(n):
# Converting decimal to binary
# and removing the prefix(0b)
return bin(n).replace("0b", "")

# Driver code
if __name__ == '__main__':
# calling function
# with decimal argument
print(decimalToBinary(77))
``````

``````1001101
``````

## Python 中的十进制转二进制没有内置函数

``````# Function to convert Decimal to Binary
def decimalToBinary(n):
return "{0:b}".format(int(n))
# Driver code
if __name__ == '__main__':
print(decimalToBinary(77))
``````

``````1001101
``````

## 快速忍法

``````# Function to convert Decimal to Binary
def decimalToBinary(n):
return bin(n)[2:]
# Driver code
if __name__ == '__main__':
print(decimalToBinary(24))
``````

``````11000
``````

## 使用按位移位运算符>>

``````# Function to convert Decimal to Binary
def decimalToBinary(n):
binary_representation = ''
while n > 0:
binary_representation = str(n % 2) + binary_representation
n = n >> 1
return binary_representation

# Driver code
if __name__ == '__main__':
print(decimalToBinary(24))
``````

``````11000
``````

## 使用内置格式化方法

Python 中的 format 方法提供了一种灵活方便的方法将十进制数转换为二进制表示形式。此方法允许精确控制输出的格式，使其成为寻求二进制表示的清晰度和自定义的开发人员的宝贵工具。

``````# Function to convert Decimal to Binary
def decimalToBinary(n):
binary_representation = format(n, 'b')
return binary_representation

# Driver code
if __name__ == '__main__':
print(decimalToBinary(42))
``````

``````101010
``````

1.15 GEEK