Created
January 6, 2016 03:14
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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