Base Conversion Module

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: Jun 2005
Posts: 3
Reputation: lapo3399 is an unknown quantity at this point 
Solved Threads: 0
lapo3399 lapo3399 is offline Offline
Newbie Poster

Base Conversion Module

 
0
  #1
Nov 23rd, 2008
I'm new to Python, and as I was coding for Project Euler to develop my skills in this language, I needed a function for converting between two bases. I know that int() can convert anything to base 10, but before I looked for a Python module concerning this math, I thought it would be a good idea to try and code one myself. Please, let me know if there is anything inefficient or in bad style so that I can improve.

It can handle A-Z notation (input both lower- and uppercase), any bases between 2 and 36, and catches problems related in invalid bases.

  1. """
  2. Matt Laporte <lapo3399@gmail.com> 2008
  3. ---
  4. Base conversion tools. Allows for A-Z notation for digits greater than 9.
  5. """
  6. from types import StringType
  7.  
  8. def inBase(num, base, fromBase = 10, result = ''):
  9. """
  10. Converts any number in fromBase to its representation in base.
  11. Defaults to converting to base_num from base_10.
  12. """
  13. if result == '':
  14. #First call checks and corrections.
  15. if num == 0: return '0'
  16. base = __check(base)
  17. if fromBase != 10:
  18. fromBase = __check(fromBase)
  19. """ In order to maintain the simplicity of the actual
  20. conversion, this converts the number to base_10. """
  21. num = toBase10(num, fromBase)
  22. fromBase = 10
  23. if num < 0:
  24. #Further simplification for the conversion component.
  25. result = '-' + result
  26. num = -1 * num
  27. if num == 0: return result #Return the final result when num has been handled.
  28. else:
  29. #Conversion. This builds up result and eats away at num.
  30. thisDigit = num%base
  31. if thisDigit > 9: thisDigit = chr(thisDigit + 55) #Accounting for A-Z digits.
  32. else: thisDigit = str(thisDigit)
  33. return inBase(num/base, base, fromBase, thisDigit + result)
  34.  
  35. def __check(base):
  36. """
  37. Verifies that a given base is 2-9 or A-Z.
  38. Converts any base from A-Z to 10-35 for numerical calculations.
  39. Should be used in the form: base == __check(base).
  40. """
  41. if type(base) == StringType and ((ord(base) > 96) and (ord(base) < 123)):
  42. #Correct a-z to A-Z
  43. base = chr(ord(base)-32)
  44. if type(base) == StringType and ((ord(base) > 64) and (ord(base) < 91)):
  45. #Correct A-Z to 10-35
  46. return (ord(base) - 55)
  47. elif type(base) != type(1) or type(base) == StringType:
  48. #Not an integer, or any string other than A-Z.
  49. raise TypeError, 'invalid base type for inBase()'
  50. if base <= 1 or base > 36:
  51. raise ValueError, 'invalid base for inBase(): %s' % base
  52. return base
  53.  
  54. def toBase10(num, base):
  55. """
  56. Converts any number represented in base to its base_10 representation.
  57. """
  58. sum = 0
  59. parseNum = str(num)
  60. indices = range(len(parseNum)) #Exponents depend on digit place, indices necessary.
  61. for i in indices:
  62. #Add the decimal representations of the digits.
  63. sum += int(parseNum[i])*base**int(indices[::-1][i])
  64. return sum

p.s. I haven't found the Python standard library function for any of this yet. As well, having a little experience in C, C++, Java, etc, I can say that Python is amazing. This -- and I know to be careful -- mutability and interchangeability (that is heresy in C) makes everything so easy in Python.

Edit: I used timeit. Although toBase10 was an attempt to imitate int() for the purpose of experiment, it is 10-15 times slower, so using int() in place of toBase10: 1 million executions of inBase with fromBase = 10 took around 10 seconds, with fromBase != 10 took around 20. I think this is pretty bad...
Last edited by lapo3399; Nov 23rd, 2008 at 11:56 pm. Reason: update on execution times
Reply With Quote Quick reply to this message  
Join Date: Jul 2008
Posts: 1,067
Reputation: jlm699 is a jewel in the rough jlm699 is a jewel in the rough jlm699 is a jewel in the rough jlm699 is a jewel in the rough 
Solved Threads: 267
Sponsor
jlm699's Avatar
jlm699 jlm699 is offline Offline
Knows where his Towel is

Re: Base Conversion Module

 
0
  #2
Nov 24th, 2008
As far as conversions are concerned there are a number of functions:
int(x [,base]) converts x to an integer
long(x [,base]) converts x to a long integer
float(x) converts x to a floating-point number
complex(real [,imag]) creates a complex number
chr(x) converts an integer to a character
unichr(x) converts an integer to a Unicode character
ord(c) converts a character to its integer value
hex(x) converts an integer to a hexadecimal string
oct(x) converts an integer to an octal string
Make sure you take note that int() and long() can take numbers of a different base, provided that you specify which base you are converting from, ie:
  1. >>> int(0xAF)
  2. 175
  3. >>> int('101',2)
  4. 5
  5. >>> int('0xaf3', 16)
  6. 2803
  7. >>>
1. Use Code Tags.
2. Homework? Show Effort.
3. Keep discussions on the forum: no PMs
Reply With Quote Quick reply to this message  
Join Date: Mar 2007
Posts: 110
Reputation: solsteel is on a distinguished road 
Solved Threads: 31
solsteel solsteel is offline Offline
Junior Poster

Re: Base Conversion Module

 
0
  #3
Nov 24th, 2008
I would like to share this function that converts a number in base 10 to any base between 2 and 36. Originally it was limited to bases 2-16.
  1. import string
  2.  
  3. def convDecToBase(num, base, dd=False):
  4. if not 2 <= base <= 36:
  5. raise ValueError, 'The base number must be between 2 and 36.'
  6. if not dd:
  7. dd = dict(zip(range(36), list(string.digits+string.ascii_lowercase)))
  8. if num == 0: return ''
  9. num, rem = divmod(num, base)
  10. return convDecToBase(num, base, dd)+dd[rem]

Example:
>>> convDecToBase(100000, 36)
'255s'
>>> int('255s', 36)
100000
>>>

Matt, Welcome to Python, and you're right about int(). No point reinventing the wheel!
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the Python Forum


Views: 1598 | Replies: 2
Thread Tools Search this Thread



Tag cloud for Python
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC