Python-Converting binary to decimal

2019-10-10 07:29发布

问题:

Im doing a colledge assignment which is have us create a python program to convert binary to decimal without using the bin() function or list(). I'm plan to have each 1's and 0's stored in a function which will be multiplied later. However, I'm not sure how am i suppose to do so

回答1:

Well, you could pass the binary number as a string, and iterate over it in reverse order, multiplying each 0 or 1 by 2^n, where n is a number incremented at each loop cycle.

def bin2dec(b):
    number = 0
    counter = 0
    for i in b[::-1]: # Iterating through b in reverse order
        number += int(i)*(2**counter)
        counter += 1

    return number

bin2dec("101010") # 42

EDIT : Like Byte Commander did, you could also use enumerate in the loop instead of a manuel counter, it serve the same purpose.

def bin2dec(b):
    number = 0
    for idx, num in enumerate(b[::-1]): # Iterating through b in reverse order
        number += int(num)*(2**idx)

    return number


回答2:

Simple one-liner using list comprehension:

decimal = sum(int(bit) * 2**rank for rank, bit in enumerate(reversed(binary)))


回答3:

There's no need to reverse the bit string, or use indices. You can use bitwise operators for this simple transformation.

Here's some Python 2 / Python 3 code:

from __future__ import print_function

def bin_to_dec(bits):
    n = 0
    for b in bits:
        n = (n << 1) | (b == '1')
    return n

# Test

for i in range(16):
    bits = format(i, 'b')
    n = bin_to_dec(bits)
    print('{0:2}: {1:>4} {2:2}'.format(i, bits, n))

output

 0:    0  0
 1:    1  1
 2:   10  2
 3:   11  3
 4:  100  4
 5:  101  5
 6:  110  6
 7:  111  7
 8: 1000  8
 9: 1001  9
10: 1010 10
11: 1011 11
12: 1100 12
13: 1101 13
14: 1110 14
15: 1111 15

This works because False has the arithmetic value of zero, and True has the arithmetic value of one, so in an arithmetic expression (b == '1') behaves like 1 if b equals '1' and 0 otherwise.

If you don't feel comfortable using the << left bit shift and | bitwise OR operators, you can use multiplication and addition instead. Simply replace

n = (n << 1) | (b == '1')

with

n = (n * 2) + (b == '1')