Skip to content

Instantly share code, notes, and snippets.

@py-in-the-sky
Created December 30, 2017 15:38
Show Gist options
  • Save py-in-the-sky/d8c920fe041506a61eea9f87894e6c4a to your computer and use it in GitHub Desktop.
Save py-in-the-sky/d8c920fe041506a61eea9f87894e6c4a to your computer and use it in GitHub Desktop.
Convert a number from base 10 to another base.
"""
Written after seeing a similar program in the MIT/EDX course
Advanced Software Construction in Java.
"""
def convert(n, base):
assert 2 <= base <= 16
if n == 0:
return "0"
elif n < 0:
return "-" + _convert(-n, base)
else:
return _convert(n, base)
def _convert(n, base):
result = []
while n > 0:
leftmost_digit = "0123456789abcdef"[n%base]
result.append(leftmost_digit)
n /= base
return "".join(reversed(result))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment