Editor

Convert Between Bases

#88 · Math · Intermediate · 75 XP · about 14 min

We usually count in base 10, but computers like base 2 (binary) and base 16 (hexadecimal), and any base from 2 to 36 works: after the digits 0 to 9 come the letters A to Z, so in base 16, A means 10 and F means 15.

Write convert_base(digits, from_base, to_base). digits is a string holding a number written in from_base; return the same number written in to_base, as a string. Use uppercase letters, no leading zeros, and a - in front of a negative number. Zero is written '0'.

Examples

convert_base('255', 10, 16)    # returns 'FF'
convert_base('FF', 16, 2)      # returns '11111111'
convert_base('-101', 2, 10)    # returns '-5'
convert_base('ZZ', 36, 10)     # returns '1295'

In base 36, Z means 35, so ZZ is 35 × 36 + 35 = 1295.

Constraints

  • 2 <= from_base, to_base <= 36
  • digits is a valid number in from_base: an optional -, then 1 to 40 digits. Letters may be uppercase or lowercase, and there may be leading zeros.

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.