Skip to content

Instantly share code, notes, and snippets.

@matxpg
Created July 5, 2014 06:25
Show Gist options
  • Save matxpg/fdc8ef288251b34c1935 to your computer and use it in GitHub Desktop.
Save matxpg/fdc8ef288251b34c1935 to your computer and use it in GitHub Desktop.
decimal to base conversion
#rem: int, int -> int
#print the remainder of (x/n)
def rem(x,n):
#prevent division by zero
assert(n != 0)
return x % n
def dec2b (xIn,b):
""" Convert n from base 10 (decimal) to base b, printing steps and result. """
assert(b > 1)
result = []
while(xIn > 0):
print xIn, '/', b, ' R', rem(xIn,b)
xIn,r = divmod(xIn,b)
result.append(r)
printResult = ''.join(map(str,result))[::-1]
return printResult
#TODO: Implement hexadecimal lettering!!!
@matxpg
Copy link
Author

matxpg commented Jul 5, 2014

#example: prints conversions of 2^1, 2^2, 2^3 to their binary format.
#easy to verify - 2 ^ x in binary is 1 followed by x zeros
for x in range(1,4):
    print 2**x,':\n'
    print dec2b(2**x,2),'\n'

output:

2 :

2 / 2 R 0
1 / 2 R 1
10

4 :

4 / 2 R 0
2 / 2 R 0
1 / 2 R 1
100

8 :

8 / 2 R 0
4 / 2 R 0
2 / 2 R 0
1 / 2 R 1
1000

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment