Answers for "convert between bases python"

1

python convert base

# add as many different characters as you want
alpha = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"


def convert(num, base=2):
    assert base <= len(alpha), f"Unable to convert to base {base}"
    converted = ""
    while num > 0:
        converted += alpha[num % base]
        num //= base

    if len(converted) == 0:
        return "0"
    return converted[::-1]
  

print(convert(15, 8))  # 17
Posted by: Guest on February-08-2020
0

convert between bases python

chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" #these are the digits you will use for conversion back and forth
charsLen = len(chars)

def numberToStr(num):
  s = ""
  while num:
    s = chars[num % charsLen] + s
    num //= charsLen

  return(s)

def strToNumber(numStr):
  num = 0
  for i, c in enumerate(reversed(numStr)):
    num += chars.index(c) * (charsLen ** i)

  return(num)
Posted by: Guest on March-14-2020

Code answers related to "convert between bases python"

Python Answers by Framework

Browse Popular Code Answers by Language