Skip to content

Instantly share code, notes, and snippets.

@vitalizzare
Last active December 12, 2021 18:00
Show Gist options
  • Select an option

  • Save vitalizzare/a64ef65e9e312eb6f1d0b5cbabf57725 to your computer and use it in GitHub Desktop.

Select an option

Save vitalizzare/a64ef65e9e312eb6f1d0b5cbabf57725 to your computer and use it in GitHub Desktop.
Number Systems and Radix Conversion (converting numbers to a given number base)
# python >= 3.8
assert (sys.version_info.major == 3 and
sys.version_info.minor >= 8)
from math import log
def convert(num:int, base=3) -> list:
'''Return a list of "digits" representing num in the given base,
ordered from lower to higher positions'''
width, num = int(1 + log(num, base)), (num,)
return [(num := divmod(num[0], base))[1] for _ in range(width)]
from math import log
import string
DIGIT_CODES = string.digits + string.ascii_uppercase
SUB_DIGITS = '₀₁₂₃₄₅₆₇₈₉' # '\N{subscript zero}\N{subscript one} ... '
def number_to_string(num:int, base=3) -> str:
'''Return a string representation of num in a base positional numeral system
>>> number_to_string(24)
'220₍₃₎'
>>> number_to_string(255, 16)
'FF₍₁₆₎'
>>> number_to_string(36**2 - 1, 36)
'ZZ₍₃₆₎'
'''
assert num > 0 and 2 <= base <= 36 # 10 digits + 26 latin letters
width, num = int(1 + log(num, base)), (num,)
digits = [(num := divmod(num[0], base))[1] for _ in range(width)]
digits = ''.join(DIGIT_CODES[i] for i in digits[::-1])
base_mark = ('\N{subscript left parenthesis}' +
''.join(SUB_DIGITS[int(i)] for i in str(base)) +
'\N{subscript right parenthesis}')
return digits + base_mark
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment