VOOZH about

URL: https://www.geeksforgeeks.org/dsa/convert-a-number-from-base-a-to-base-b/

⇱ Convert a number from base A to base B - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Convert a number from base A to base B

Last Updated : 23 Jul, 2025

Given two positive integers A and B and a string S of size N,  denoting a number in base A, the task is to convert the given string S from base A to base B.

Examples:

Input: S = "10B", A = 16, B = 10
Output: 267
Explanation: 10B in hexadecimal (base =16) when converted to decimal (base =10) is 267.

Input: S = "10011", A = 2, B = 8
Output: 23
Explanation: 10011 in binary (base =2) when converted to octal (base = 8) is 23. 

Approach: Number systemsis the technique to represent numbers in the computer system architecture. The computer architecture supports the following number systems:

  • Binary Number System (Base 2): The binary number system only consists of two digits, 0s and 1s. The base of this number system is 2.
  • Octal Number System (Base 8): The octal number system consists of 8 digits ranging from 0 to 7.
  • Decimal Number System (Base 10): The decimal number system consists of 10 digits ranging from 0 to 9.
  • Hexadecimal Number System (Base 16): The hexadecimal number system consists of 16 digits with 0 to 9 digits and alphabets A to F. It is also known as alphanumeric code as it consists of both number and alphabets.

To convert a number from base A to base B, the idea is to first convert it to its decimal representation and then convert the decimal number to base B 

Conversion from any base to Decimal: The decimal equivalent of the number "str" in base "base" is equal to 1 * str[len - 1] + base * str[len - 2] + (base)2 * str[len - 3] + ...

Conversion from Decimal to any base: 
The decimal number "inputNum" can be converted to a number on base "base" by repeatedly dividing inputNum by base and store the remainder. Finally, reverse the obtained string to get the desired result. 

Below is the implementation of the above approach:


Output: 
267

 

Time Complexity: O(N)
Auxiliary Space: O(N)


 

Comment
Article Tags:
Article Tags: