Skip to content

Instantly share code, notes, and snippets.

@AnthonyBloomer
Created January 6, 2016 03:14
Show Gist options
  • Save AnthonyBloomer/30421d06235e912e27fc to your computer and use it in GitHub Desktop.
Save AnthonyBloomer/30421d06235e912e27fc to your computer and use it in GitHub Desktop.
Convert a decimal to a given base and then back to it's decimal representation.
# convert a decimal to a given base
def d2b(dec, base):
stack = []
result = ''
while dec > 0:
rem = dec % base
dec = dec / base
stack.append(rem)
while stack:
result += str(stack.pop())
print result
# convert the number back to its decimal representation
def b2d(num, base):
result = 0
for n in str(num):
result *= base
result += int(n)
print result
d2b(10,16)
b2d(101010101010101010,2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment