Base Converter - Problem

Write functions to convert a number from any base (2-16) to any other base.

Your function should take three parameters:

  • number: The number to convert (as a string)
  • fromBase: The base of the input number (integer from 2 to 16)
  • toBase: The target base for conversion (integer from 2 to 16)

For bases greater than 10, use uppercase letters A-F to represent digits 10-15.

Note: Handle invalid inputs by returning an empty string.

Input & Output

Example 1 — Binary to Hexadecimal
$ Input: number = "1010", fromBase = 2, toBase = 16
Output: "A"
💡 Note: Binary 1010 = 1×8 + 0×4 + 1×2 + 0×1 = 10 in decimal, then 10 in decimal = A in hexadecimal
Example 2 — Decimal to Binary
$ Input: number = "10", fromBase = 10, toBase = 2
Output: "1010"
💡 Note: Decimal 10 divided by 2 repeatedly: 10÷2=5 R0, 5÷2=2 R1, 2÷2=1 R0, 1÷2=0 R1, reading remainders backwards gives 1010
Example 3 — Same Base
$ Input: number = "123", fromBase = 10, toBase = 10
Output: "123"
💡 Note: Same base conversion returns the original number unchanged

Constraints

  • 2 ≤ fromBase, toBase ≤ 16
  • 1 ≤ number.length ≤ 30
  • number contains only valid digits for fromBase
  • Digits 0-9 for values 0-9, letters A-F for values 10-15

Visualization

Tap to expand
Base Converter: Binary 1010 to HexadecimalINPUTBinary Number1010Base 2From Base: 2To Base: 16Digits: 1, 0, 1, 0Valid for base 2 ✓ALGORITHM STEPS1Binary → Decimal1×8 + 0×4 + 1×2 + 0×1 = 102Decimal → Hexadecimal10 ÷ 16 = 0 remainder 10Remainder 10 = A in hex3Validate ResultA is valid hex digitFINAL RESULTHexadecimal NumberABase 16Conversion: 1010₂ → A₁₆Decimal equivalent: 10Result verified ✓💡Key Insight:Using decimal as an intermediate base eliminates the need for 210 different conversion tables.Any base → decimal → any base works universally for all base combinations.TutorialsPoint - Base Converter | Two-Step Conversion via Decimal
Asked in
Google 12 Amazon 8 Microsoft 6
15.0K Views
Medium Frequency
~15 min Avg. Time
420 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen