Python如何实现二进制和十进制互相转换()

编写Python代码, 将十进制数转换为等效的二进制数, 反之亦然。
例子:

From decimal to binaryInput : 8Output : 1 0 0 0From binary to decimalInput : 100Output : 4

推荐:请尝试以下方法{IDE}首先, 在继续解决方案之前。十进制到二进制
Keep calling conversion function with n/2till n > 1, later perform n % 1 to get MSB of converted binary number.Example :- 71). 7/2 = Quotient = 3(grater than 1), Remainder = 1.2). 3/2 = Quotient = 1(not grater than 1), Remainder = 1.3). 1%2 = Remainder = 1.Therefore, answer is 111.

# Function to print binary number for the # input decimal using recursion def decimalToBinary(n): if (n > 1 ): # divide with integral result # (discard remainder) decimalToBinary(n / / 2 ) print (n % 2 , end = ' ' )# Driver code if __name__ = = '__main__' : decimalToBinary( 8 ) print ( "\n" ) decimalToBinary( 18 ) print ( "\n" ) decimalToBinary( 7 ) print ( "\n" )

输出如下:
1 0 0 0 1 0 0 1 0 1 1 1

使用bin()十进制转换为二进制:
# Function to convert Decimal number # to Binary numberdef decimalToBinary(n): return bin (n).replace( "0b" , "")# Driver code if __name__ = = '__main__' : print (decimalToBinary( 8 )) print (decimalToBinary( 18 )) print (decimalToBinary( 7 ))

【Python如何实现二进制和十进制互相转换()】输出如下:
100010010111

二进制到十进制
Example -: 10111). Take modulo of given binary number with 10. (1011 % 10 = 1)2). Multiply rem with 2 raised to the powerit's position from right end. (1 * 2^0)Note that we start counting position with 0. 3). Add result with previously generated result.decimal = decimal + (1 * 2^0)4). Update binary number by dividing it by 10.(1011 / 10 = 101)5). Keep repeating upper steps till binary > 0.Final Conversion -: (1 * 2^3) + (0 * 2^2) +(1 * 2^1) + (1 * 2^0) = 11

# Function calculates the decimal equivalent # to given binary numberdef binaryToDecimal(binary):binary1 = binary decimal, i, n = 0 , 0 , 0 while (binary ! = 0 ): dec = binary % 10 decimal = decimal + dec * pow ( 2 , i) binary = binary / / 10 i + = 1 print (decimal)# Driver code if __name__ = = '__main__' : binaryToDecimal( 100 ) binaryToDecimal( 101 ) binaryToDecimal( 1001 )

输出如下:
459

使用int()的二进制到十进制:
# Function to convert Binary number # to Decimal numberdef binaryToDecimal(n): return int (n, 2 )# Driver code if __name__ = = '__main__' : print (binaryToDecimal( '100' )) print (binaryToDecimal( '101' )) print (binaryToDecimal( '1001' ))

输出如下:
459

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。
注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。
首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。

    推荐阅读