Skip to main content

Base conversion algorithms in python


Ascii to Integer
Input - '123'
Output - 123
def atoi(s):
  res = 0
  for i in range(len(s)):
    n = ord(s[i]) - ord('0')
    res = res * 10 + n
  return res


Integer to ASCII
Input - 123
Output - '123'
def itoa(num):
  res = ""
  while num:
    n = num % 10
    res += chr(ord(str(n))) or res += str(n)
    num = num / 10
  return res[::-1]

Decimal to binary
Input - 5
Output - 101
def decimal_to_binary(num):
  res = ""
  while num:
    #even number and has 0
    if not num % 2:
      res += '0'
    else:
      res += '1'
    num = num / 2
  return res[::-1]

Binary to decimal
Input - 101
Output - 5
def binary_to_decimal(binary_str):
  res, shift = 0, 0
  for i in range(len(binary_str)-1, -1, -1):
        if int(binary_str[i]):
          res += (1 << shift)
        shift += 1
  return res

Hexadecimal to decimal 
Input - 7ED
Output - 2029

HEX_DEC = {'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}
def hex_to_decimal(hex_str):
  index, res = 0, 0
  for i in range(len(hex_str)-1, -1, -1):
    res += HEX_DEC[hex_str[i]] * (16 ** index)
    index += 1
  return res

Deciaml to Hexadecimal 
Input - 2029
Output - 7ED

DEC_HEX = {0:'0', 1:'1', 2:'2', 3:'3', 4:'4', 5:'5', 6:'6', 7:'7', 8:'8', 9:'9', 10:'A', 11:'B', 12:'C', 13:'D', 14:'E', 15:'F'}
def decimal_to_hex(dec_num):
  res = ""
  while dec_num:
    rem = dec_num % 16
    res += DEC_HEX[rem]
    dec_num = dec_num / 16
  return res[::-1 

Comments