Python | 不使用库函数将二进制数转换为十进制

Given a binary number and we have to convert it into decimal without using library function.

给定一个二进制数,我们必须在不使用库函数的情况下将其转换为十进制数。

Example:

例:

    Input: 
    1010

    Output: 
    10

Python code to convert binary to decimal

Python代码将二进制转换为十进制

# Python code to convert binary to decimal
def binToDec(bin_value):
    
    # converting binary to decimal
    decimal_value = 0
    count = 0
    
    while(bin_value != 0):
        digit = bin_value % 10
        decimal_value = decimal_value + digit * pow(2, count)
        bin_value = bin_value//10
        count += 1

    # returning the result        
    return decimal_value

# main code
if __name__ == '__main__':
    binary = int(input("Enter a binary value: "))
    print("decimal of binary ", binary, " is: ", binToDec(binary))

    binary = int(input("Enter another binary value: "))
    print("decimal of binary ", binary, " is: ", binToDec(binary))

    binary = int(input("Enter another binary value: "))
    print("decimal of binary ", binary, " is: ", binToDec(binary))  

Output

输出量

Enter a binary value: 1010  
decimal of binary  1010  is:  10  
Enter another binary value: 1111000011  
decimal of binary  1111000011  is:  963 
Enter another binary value: 10000001 
decimal of binary  10000001  is:  129     


翻译自: https://www.includehelp.com/python/convert-the-binary-number-to-decimal-without-using-library-function.aspx

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值