Skip to content

Instantly share code, notes, and snippets.

@f0t0n
Created February 24, 2012 22:33
Show Gist options
  • Save f0t0n/1904233 to your computer and use it in GitHub Desktop.
Save f0t0n/1904233 to your computer and use it in GitHub Desktop.
Convert an integer number to another system - such as to binary, hex, etc. (Python example)
#!/usr/bin/env python
from itertools import chain
from sys import exit
def num_to_bin():
try:
original_number = int(input('Chose the number: '))
basis = int(input('Chose the basis (up to 32): '))
if(basis > 32):
raise ValueError('The basis can be up to 32.')
except ValueError as e:
print('Number is incorrect')
exit(e)
num = original_number
number_dict = {}
codes = chain(range(0, 10), range(97, 123))
for code in codes:
if code < 10:
number_dict[code] = code
else:
number_dict[code - 87] = chr(code)
res = ''
while True:
quotinent = num % basis
res += str(number_dict[quotinent])
num //= basis
if num == 0:
break
res = res[::-1]
print(original_number, ' - ', res)
try:
num_to_bin()
except SystemExit as e:
print(e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment