簡體   English   中英

如何在不使用bin方法的情況下將二進制轉換為十進制

[英]how can I convert binary to decimal without using bin method

每當我運行我的代碼時,我都會收到一個 TypeError,說“並非所有的爭論都在字符串格式化過程中被轉換”,我嘗試使用 str() 來解決沒有被轉換的問題,但我遇到了更多的錯誤。

這是我的代碼:

def decimalToBinary(num):

bits = " "

while(num > 0):
   
    bits = str(num%2) + bits
    num = num//2
    
    return bits

def binaryToDecimal(bits):

    deciNum = 0
    powers = 0

    for i in reversed(bits):
    
        deciNum = 2 **powers** (bits % 10)
        bits /=  10
        powers += 1
    
        return deciNum

#program tester
for i in range(135, 146):
x = decimalToBinary(i)
deciNum = binaryToDecimal(x)
print(str(decimal))+ ' is '+ ' in Binary.'

我在“deciNum = 2 ** powers ** (bits%10)

嘗試這個:

def binaryToDecimal(b_num: str) -> int:
    d_num = 0
    for i in range(len(b_num)):
        digit = b_num.pop()
        if digit == '1':
            d_num = d_num + 2**i
    return d_num

請注意, b_num是一個字符串,而不是一個 int。 所以你需要以這種方式使用這個函數binaryToDecimal('101') (而不是以這種方式binaryToDecimal(101) )。

要回答帖子的標題並使類型與您的程序保持一致:

import math

def binaryToDecimal(bits):

    # Initialize integer for number.
    num = 0

    # For each bit, multiply by power of 2 corresponding to its position.
    #  Then, add that power of 2 to the total counter.
    for i in range(len(bits)):
        num += int(bits[i]) * (2 ** (len(bits)-i-1))

    # Return integer type.
    return str(num)

def decimalToBinary(num):

    # Determine how many bits represent the decimal number.
    num_of_bits = int(math.log(num, 2)) + 1

    bits = ''

    # Shift the number over 1 more place to the right in each iteration.
    #  Then test the sign of the bit with AND.
    for i in reversed(range(num_of_bits)):
        bits += str(int(1&(num>>i)))
    
    return bits


for i in range(135, 146):
    x = decimalToBinary(i)
    deciNum = binaryToDecimal(x)
    print(str(deciNum)+ ' is '+ str(x)+' in Binary.')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM