saltekar
saltekar

Reputation: 71

Pythonic way to do base conversion

I am a complete beginner to Python. I wrote some code to perform base conversion and I was wondering if there were better alternatives that were shorter to code (one-liners) or significantly faster. The code looks ugly and feels "non-Pythonic" though being a beginner I should not have any such opinion. Any feedback to improve the code would be appreciated. This is purely for learning purposes.

#!/usr/bin/env python

import math

def number_to_digits( number, radix ):
  'Converts a number into a vector of digits in given radix'
  digits = [0]*int(math.ceil(math.log(number,radix)))
  for ii in range(len(digits)):
    (number,digit) = divmod(number,radix)
    digits[ii] = digit
  return digits

def digits_to_number( digits, radix ):
  'Converts a vector of non-negative digits in given radix into a number'
  number = 0;
  for ii in range(len(digits)-1,-1,-1):
    number *= radix
    number += digits[ii]
  return number

if __name__ == '__main__':
  try:
    number = int(raw_input('Enter number: '))
    if number <= 0: raise ValueError()
    radix = int(raw_input('Enter radix: '))
    if radix <= 0: raise ValueError()
    digits = number_to_digits(number,radix)
    print digits
    number_again = digits_to_number(digits,radix)
    if not number_again == number:
      print 'test failed'
  except ValueError:
    print 'unexpected input'

A sample session on the terminal produces:

Enter number: 44
Enter radix: 6
[2, 1, 1]

It is easy to check that 2 + 1*6 + 1*6**2 == 44. Thanks!

Upvotes: 3

Views: 10059

Answers (3)

Pradnya Bamane
Pradnya Bamane

Reputation: 41

Python provides some built-in functions to convert a value represented in one Integer base to another Integer base. Integer is represented in four forms i.e. decimal, binary, octal, and hexadecimal form.

Python provides built-in bin() functions to convert from non-binary number to binary number, oct() function to convert from non-octal number to octal number and hex() function to convert from non-hexadecimal number to hexadecimal number. These functions return a string literal to represent the values.

You can learn these functions from the tutorial on Integer base Conversion Functions in Python

Upvotes: 4

jastr
jastr

Reputation: 889

Here's a nice recursive version that will convert up to hexadecimal from Problem Solving with Algorithms and Data Structures

def toStr(n,base):
    convertString = "0123456789ABCDEF"
    if n < base:
        return convertString[n]
    else:
        return toStr(n//base,base) + convertString[n%base]

print(toStr(1453,16))

Upvotes: 8

Kevin Stone
Kevin Stone

Reputation: 8981

You can find (slightly) cleaner example in the following thread: Python elegant inverse function of int(string,base).

Taking the top ranked example, you can clean it up a bit to:

def digit_to_char(digit):
    if digit < 10:
        return str(digit)
    return chr(ord('a') + digit - 10)

def str_base(number, base):
    while number > 0:
        number, digit = divmod(number, base)
        yield digit_to_char(digit)

Results in:

>>> list(str_base(44, 6))
['2', '1', '1']

If you don't care about bases larger than 10, it simplifies to:

def str_base(number, base):
    if base > 10:
         raise ValueError('Base must be less than 10')
    while number > 0:
        number, digit = divmod(number, base)
        yield digit

>>> list(str_base(44, 6))
[2, 1, 1]

Upvotes: 0

Related Questions