Binary to Decimal

Harold Nelson

2/18/2020

Polynomial Interpretation

Assume that a binomial number is represented as a string.

The string ‘1101’ is converted to a decimal value using the expression \[ 1*2^3 + 1*2^2 + 0*2^1+1*2^0 \] What tells you that the highest power is 3?

Ex1

How would you get this value in python code?

Answer

The length of the string is 4.

degree = len('1101') - 1
degree
## 3

Ex2

How could you use int() to convert a binary string to a decimal value? Go to python.org and search the python 3 documentation for int().

Answer

int('1101',base = 2)
## 13

Ex3

Write your own code to convert a binary string to its decimal value.

Answer

# Get the initial values
in_string = '1011'
length = len(in_string)
exponent = length - 1
index = 0
result = 0

# Do a while loop
while index <= length - 1:
    result = result + int(in_string[index]) * 2**exponent
    exponent = exponent - 1
    index = index + 1
print(result)
## 11

Here is a for loop version.

in_string = '1011'
length = len(in_string)
exponent = length - 1
index = 0
result = 0

for index in range(length):
    exponent = length - 1 - index
    result = result + int(in_string[index]) * 2**exponent
print(result)
## 11

Ex4

What would need to be changed to use this code to convert from hexadecimal to a decimal?

Answer

  1. Instead of 2exponent, we would need 16exponent.

  2. int(in_string[index]) would fail with hex digits above 9.

Ex5

Write a program to convert from hexadecimal to decimal.

Answer

# Hex to Decimal
hd = {'0':0,
      '1':1,
      '2':2,
      '3':3,
      '4':4,
      '5':5,
      '6':6,
      '7':7,
      '8':8,
      '9':9,
      'A':10,
      'B':11,
      'C':12,
      'D':13,
      'E':14,
      'F':15}

s = 'A5AF'
length = len(s)
result = 0
for index in range(length):
    exponent = length - 1 - index
    result = result + hd[s[index]] * 16**exponent
print(result)
## 42415

Ex6

Use the int() function to do the same conversion.

s = 'A5AF'
int(s, base = 16)
## 42415

Ex7

In order to write a program to convert from decimal to binary, the first step is to determine the highest power of 2 we need. The idea is to find the first power that’s too large and then reduce it by 1. Write a python program to determine this power.

Answer

dec = 8
power = 0
while 2**power <= dec:
    power = power + 1
highest = power - 1    
print(highest)    
## 3

Ex8

Now use this to write a python program which converts from decimal to binary. Test it with decimal values, one of which is an even power of 2.

dec = 17
power = 0
while 2**power <= dec:
    power = power + 1
highest = power - 1    

binary = ''
power = highest
left_to_do = dec
while left_to_do > 0:
    contrib = left_to_do//2**power
    left_to_do = left_to_do - contrib*2**power
    binary = binary + str(contrib)
    power = power - 1
while power >= 0:
    power = power - 1
    binary = binary + '0'
print(binary)
## 10001