Posted on by Kalkicode
Code Conversion

Convert a number from decimal to other base

The process of converting a number from decimal (base 10) to another base involves dividing the decimal number by the desired base and obtaining the remainders. The remainders, in reverse order, form the converted number in the desired base. This article explains the algorithm and provides an example in Java code for converting decimal numbers to other bases.

Problem Statement

Given a decimal number and a destination base, we want to convert the decimal number to the specified base. For example, converting the decimal number 55 to binary (base 2) should yield the result 110111.

Example

Let's consider the example of converting the decimal number 125 to hexadecimal (base 16). We'll follow the algorithm step by step to understand the process:

  1. Initialize the decimal number as 125 and the destination base as 16.
  2. Set the flag to false (indicating a positive number).
  3. Initialize an empty string to store the result.
  4. Iterate until the decimal number is greater than 0:
    1. Compute the remainder of the decimal number divided by the destination base.
    2. Convert the remainder to its corresponding character representation (0-9 or A-F).
    3. Prepend the converted character to the result string.
    4. Update the decimal number by dividing it by the destination base.
  5. If the number was negative (flag is true), prepend a "-" sign to the result string.
  6. The resulting string is the converted number in the desired base.

In our example, the conversion process would proceed as follows:

  1. 125 % 16 = 13, converted to 'D'
  2. 125 / 16 = 7
  3. 7 % 16 = 7, converted to '7'
  4. 7 / 16 = 0

The resulting string is "7D", which is the hexadecimal representation of the decimal number 125.

Algorithm

The following is the algorithm to convert a decimal number to another base:

actual_value(num):
	if num >= 0 and num <= 9:
		return char(num + '0')
	else:
		return char(num - 10 + 'A')

decimal_to_other(decimal_number, destination_base):
	flag = False
	if decimal_number < 0:
		decimal_number = -decimal_number
		flag = True

	result = ""

	while decimal_number > 0:
		result = actual_value(decimal_number % destination_base) + result
		decimal_number = decimal_number / destination_base

	if flag == True:
		result = "-" + result

	print("Result: " + result)

Code Explanation

The code defines a class called "NumberConversion" with two methods: "actual_value()" and "decimal_to_other()". The "actual_value()" method is used to convert a number to its corresponding character representation, either a digit or a character from 'A' to 'F' for bases greater than 10.

The "decimal_to_other()" method takes a decimal number and a destination base as inputs. It initializes the flag to false and a result string to store the converted number. If the decimal number is negative, it updates the number and sets the flag to true.

The method then iterates until the decimal number is greater than 0. In each iteration, it calculates the remainder of the division of the decimal number by the destination base, converts it to the corresponding character using the "actual_value()" method, and prepends it to the result string. After that, it updates the decimal number by dividing it by the destination base.

Finally, if the flag is true, indicating a negative number, it prepends a "-" sign to the result string. The resulting string is then printed as the converted number in the desired base.

Program solution

// Java program
// Convert a number from decimal to other base
class NumberConversion
{
	//Get valid value
	public char actual_value(int num)
	{
		if (num >= 0 && num <= 9)
		{
			return (char)(num + '0');
		}
		else
		{
			return (char)(num - 10 + 'A');
		}
	}
	//Convert decimal number in given base number
	public void decimal_to_other(int decimal_number, int destination_base)
	{
		System.out.print("\n Decimal Number   : " + decimal_number);
		System.out.print("\n Destination Base : " + destination_base);
		boolean flag = false;
		if (decimal_number < 0)
		{
			decimal_number = -decimal_number;
			flag = true;
		}
		//This is used to store result
		String result = "";
		//Transform decimal to other base
		while (decimal_number > 0)
		{
			result = (actual_value(decimal_number % destination_base)) + result;
			decimal_number /= destination_base;
		}
		if (flag == true)
		{
			result = "-" + result;
		}
		//Display result
		System.out.print("\n Result : " + result + "\n");
	}
	public static void main(String[] args) throws Exception
	{
		NumberConversion obj = new NumberConversion();
		//Test case
		obj.decimal_to_other(55, 2);
		obj.decimal_to_other(125, 16);
		obj.decimal_to_other(125, 8);
      	obj.decimal_to_other(-28, 16);
		obj.decimal_to_other(24, 4);
      	obj.decimal_to_other(2124, 16);
	}
}

Output

 Decimal Number   : 55
 Destination Base : 2
 Result : 110111

 Decimal Number   : 125
 Destination Base : 16
 Result : 7D

 Decimal Number   : 125
 Destination Base : 8
 Result : 175

 Decimal Number   : -28
 Destination Base : 16
 Result : -1C

 Decimal Number   : 24
 Destination Base : 4
 Result : 120

 Decimal Number   : 2124
 Destination Base : 16
 Result : 84C
//Include header file
#include <iostream>

using namespace std;
// C++ program
// Convert a number from decimal to other base
class NumberConversion
{
	public:
		//Get valid value
		char actual_value(int num)
		{
			if (num >= 0 && num <= 9)
			{
				return (char)(num + '0');
			}
			else
			{
				return (char)(num - 10 + 'A');
			}
		}
	//Convert decimal number in given base number
	void decimal_to_other(int decimal_number, int destination_base)
	{
		cout << "\n Decimal Number   : " << decimal_number;
		cout << "\n Destination Base : " << destination_base;
		bool flag = false;
		if (decimal_number < 0)
		{
			decimal_number = -decimal_number;
			flag = true;
		}
		//This is used to store result
		string result = "";
		//Transform decimal to other base
		while (decimal_number > 0)
		{
			result = (this->actual_value(decimal_number % destination_base)) + result;
			decimal_number /= destination_base;
		}
		if (flag == true)
		{
			result = "-" + result;
		}
		//Display result
		cout << "\n Result : " << result << "\n";
	}
};
int main()
{
	NumberConversion obj = NumberConversion();
	//Test case
	obj.decimal_to_other(55, 2);
	obj.decimal_to_other(125, 16);
	obj.decimal_to_other(125, 8);
	obj.decimal_to_other(-28, 16);
	obj.decimal_to_other(24, 4);
	obj.decimal_to_other(2124, 16);
	return 0;
}

Output

 Decimal Number   : 55
 Destination Base : 2
 Result : 110111

 Decimal Number   : 125
 Destination Base : 16
 Result : 7D

 Decimal Number   : 125
 Destination Base : 8
 Result : 175

 Decimal Number   : -28
 Destination Base : 16
 Result : -1C

 Decimal Number   : 24
 Destination Base : 4
 Result : 120

 Decimal Number   : 2124
 Destination Base : 16
 Result : 84C
//Include namespace system
using System;
// C# program
// Convert a number from decimal to other base
class NumberConversion
{
	//Get valid value
	public char actual_value(int num)
	{
		if (num >= 0 && num <= 9)
		{
			return (char)(num + '0');
		}
		else
		{
			return (char)(num - 10 + 'A');
		}
	}
	//Convert decimal number in given base number
	public void decimal_to_other(int decimal_number, int destination_base)
	{
		Console.Write("\n Decimal Number   : " + decimal_number);
		Console.Write("\n Destination Base : " + destination_base);
		Boolean flag = false;
		if (decimal_number < 0)
		{
			decimal_number = -decimal_number;
			flag = true;
		}
		//This is used to store result
		String result = "";
		//Transform decimal to other base
		while (decimal_number > 0)
		{
			result = (actual_value(decimal_number % destination_base)) + result;
			decimal_number /= destination_base;
		}
		if (flag == true)
		{
			result = "-" + result;
		}
		//Display result
		Console.Write("\n Result : " + result + "\n");
	}
	public static void Main(String[] args) 
	{
		NumberConversion obj = new NumberConversion();
		//Test case
		obj.decimal_to_other(55, 2);
		obj.decimal_to_other(125, 16);
		obj.decimal_to_other(125, 8);
		obj.decimal_to_other(-28, 16);
		obj.decimal_to_other(24, 4);
		obj.decimal_to_other(2124, 16);
	}
}

Output

 Decimal Number   : 55
 Destination Base : 2
 Result : 110111

 Decimal Number   : 125
 Destination Base : 16
 Result : 7D

 Decimal Number   : 125
 Destination Base : 8
 Result : 175

 Decimal Number   : -28
 Destination Base : 16
 Result : -1C

 Decimal Number   : 24
 Destination Base : 4
 Result : 120

 Decimal Number   : 2124
 Destination Base : 16
 Result : 84C
<?php
// Php program
// Convert a number from decimal to other base
class NumberConversion
{
	//Get valid value
	public	function actual_value($num)
	{
		if ($num >= 0 && $num <= 9)
		{
			return (chr($num + ord('0')));
		}
		else
		{
			return (chr($num - 10 +  ord('A')));
		}
	}
	//Convert decimal number in given base number
	public	function decimal_to_other($decimal_number, $destination_base)
	{
		echo "\n Decimal Number   : ". $decimal_number;
		echo "\n Destination Base : ". $destination_base;
		$flag = false;
		if ($decimal_number < 0)
		{
			$decimal_number = -$decimal_number;
			$flag = true;
		}
		//This is used to store result
		$result = "";
		//Transform decimal to other base
		while ($decimal_number > 0)
		{
			$result = ($this->actual_value($decimal_number % $destination_base)) . $result;
			$decimal_number = intval($decimal_number / $destination_base);
		}
		if ($flag == true)
		{
			$result = "-". $result;
		}
		//Display result
		echo "\n Result : ". $result ."\n";
	}
}

function main()
{
	$obj = new NumberConversion();
	//Test case
	$obj->decimal_to_other(55, 2);
	$obj->decimal_to_other(125, 16);
	$obj->decimal_to_other(125, 8);
	$obj->decimal_to_other(-28, 16);
	$obj->decimal_to_other(24, 4);
	$obj->decimal_to_other(2124, 16);
}
main();

Output

 Decimal Number   : 55
 Destination Base : 2
 Result : 110111

 Decimal Number   : 125
 Destination Base : 16
 Result : 7D

 Decimal Number   : 125
 Destination Base : 8
 Result : 175

 Decimal Number   : -28
 Destination Base : 16
 Result : -1C

 Decimal Number   : 24
 Destination Base : 4
 Result : 120

 Decimal Number   : 2124
 Destination Base : 16
 Result : 84C
// Node Js program
// Convert a number from decimal to other base
class NumberConversion
{
	//Get valid value
	actual_value(num)
	{
		if (num >= 0 && num <= 9)
		{
			return (String.fromCharCode(num + '0'.charCodeAt(0)));
		}
		else
		{
			return (String.fromCharCode(num - 10 + 'A'.charCodeAt(0)));
		}
	}
	//Convert decimal number in given base number
	decimal_to_other(decimal_number, destination_base)
	{
		process.stdout.write("\n Decimal Number   : " + decimal_number);
		process.stdout.write("\n Destination Base : " + destination_base);
		var flag = false;
		if (decimal_number < 0)
		{
			decimal_number = -decimal_number;
			flag = true;
		}
		//This is used to store result
		var result = "";
		//Transform decimal to other base
		while (decimal_number > 0)
		{
			result = (this.actual_value(decimal_number % destination_base)) + result;
			decimal_number = parseInt(decimal_number / destination_base);
		}
		if (flag == true)
		{
			result = "-" + result;
		}
		//Display result
		process.stdout.write("\n Result : " + result + "\n");
	}
}

function main()
{
	var obj = new NumberConversion();
	//Test case
	obj.decimal_to_other(55, 2);
	obj.decimal_to_other(125, 16);
	obj.decimal_to_other(125, 8);
	obj.decimal_to_other(-28, 16);
	obj.decimal_to_other(24, 4);
	obj.decimal_to_other(2124, 16);
}
main();

Output

 Decimal Number   : 55
 Destination Base : 2
 Result : 110111

 Decimal Number   : 125
 Destination Base : 16
 Result : 7D

 Decimal Number   : 125
 Destination Base : 8
 Result : 175

 Decimal Number   : -28
 Destination Base : 16
 Result : -1C

 Decimal Number   : 24
 Destination Base : 4
 Result : 120

 Decimal Number   : 2124
 Destination Base : 16
 Result : 84C
#  Python 3 program
#  Convert a number from decimal to other base
class NumberConversion :
	# Get valid value
	def actual_value(self, num) :
		if (num >= 0 and num <= 9) :
			return (chr(num + ord('0')))
		else :
			return (chr(num - 10 + ord('A')))
		
	
	# Convert decimal number in given base number
	def decimal_to_other(self, decimal_number, destination_base) :
		print("\n Decimal Number   : ", decimal_number, end = "")
		print("\n Destination Base : ", destination_base, end = "")
		flag = False
		if (decimal_number < 0) :
			decimal_number = -decimal_number
			flag = True
		
		# This is used to store result
		result = ""
		# Transform decimal to other base
		while (decimal_number > 0) :
			result = (self.actual_value(decimal_number % destination_base)) + result
			decimal_number = int(decimal_number / destination_base)
		
		if (flag == True) :
			result = "-"+ result
		
		# Display result
		print("\n Result : ", result ,"\n", end = "")
	

def main() :
	obj = NumberConversion()
	# Test case
	obj.decimal_to_other(55, 2)
	obj.decimal_to_other(125, 16)
	obj.decimal_to_other(125, 8)
	obj.decimal_to_other(-28, 16)
	obj.decimal_to_other(24, 4)
	obj.decimal_to_other(2124, 16)

if __name__ == "__main__": main()

Output

 Decimal Number   :  55
 Destination Base :  2
 Result :  110111

 Decimal Number   :  125
 Destination Base :  16
 Result :  7D

 Decimal Number   :  125
 Destination Base :  8
 Result :  175

 Decimal Number   :  -28
 Destination Base :  16
 Result :  -1C

 Decimal Number   :  24
 Destination Base :  4
 Result :  120

 Decimal Number   :  2124
 Destination Base :  16
 Result :  84C
#  Ruby program
#  Convert a number from decimal to other base
class NumberConversion

	# Get valid value
	def actual_value(num)
	
		if (num >= 0 && num <= 9)
		
			return ((num + ('0'.ord)).chr).to_s
		else
		
			return ((num - 10 + ('A'.ord)).chr).to_s
		end
	end
	# Convert decimal number in given base number
	def decimal_to_other(decimal_number, destination_base)
	
		print("\n Decimal Number   : ", decimal_number)
		print("\n Destination Base : ", destination_base)
		flag = false
		if (decimal_number < 0)
		
			decimal_number = -decimal_number
			flag = true
		end
		# This is used to store result
		result = ""
		# Transform decimal to other base
		while (decimal_number > 0)
		
			result = (self.actual_value(decimal_number % destination_base)) + result
			decimal_number = decimal_number / destination_base
		end
		if (flag == true)
		
			result = "-"+ result
		end
		# Display result
		print("\n Result : ", result ,"\n")
	end
end
def main()

	obj = NumberConversion.new()
	# Test case
	obj.decimal_to_other(55, 2)
	obj.decimal_to_other(125, 16)
	obj.decimal_to_other(125, 8)
	obj.decimal_to_other(-28, 16)
	obj.decimal_to_other(24, 4)
	obj.decimal_to_other(2124, 16)
end
main()

Output

 Decimal Number   : 55
 Destination Base : 2
 Result : 110111

 Decimal Number   : 125
 Destination Base : 16
 Result : 7D

 Decimal Number   : 125
 Destination Base : 8
 Result : 175

 Decimal Number   : -28
 Destination Base : 16
 Result : -1C

 Decimal Number   : 24
 Destination Base : 4
 Result : 120

 Decimal Number   : 2124
 Destination Base : 16
 Result : 84C
// Scala program
// Convert a number from decimal to other base
class NumberConversion
{
	//Get valid value
	def actual_value(num: Int): Char = {
		if (num >= 0 && num <= 9)
		{
			return (num + '0').toChar;
		}
		else
		{
			return (num - 10 + 'A').toChar;
		}
	}
	//Convert decimal number in given base number
	def decimal_to_other(decimal: Int, base: Int): Unit = {
      	var destination_base = base;
      	var decimal_number = decimal;
		print("\n Decimal Number   : " + decimal_number);
		print("\n Destination Base : " + destination_base);
		var flag: Boolean = false;
		if (decimal_number < 0)
		{
			decimal_number = -decimal_number;
			flag = true;
		}
		//This is used to store result
		var result: String = "";
		//Transform decimal to other base
		while (decimal_number > 0)
		{
			result = ""+(actual_value(decimal_number % destination_base)) + result;
			decimal_number = (decimal_number / destination_base).toInt;
		}
		if (flag == true)
		{
			result = "-" + result;
		}
		//Display result
		print("\n Result : " + result + "\n");
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		var obj: NumberConversion = new NumberConversion();
		//Test case
		obj.decimal_to_other(55, 2);
		obj.decimal_to_other(125, 16);
		obj.decimal_to_other(125, 8);
		obj.decimal_to_other(-28, 16);
		obj.decimal_to_other(24, 4);
		obj.decimal_to_other(2124, 16);
	}
}

Output

 Decimal Number   : 55
 Destination Base : 2
 Result : 110111

 Decimal Number   : 125
 Destination Base : 16
 Result : 7D

 Decimal Number   : 125
 Destination Base : 8
 Result : 175

 Decimal Number   : -28
 Destination Base : 16
 Result : -1C

 Decimal Number   : 24
 Destination Base : 4
 Result : 120

 Decimal Number   : 2124
 Destination Base : 16
 Result : 84C
// Swift program
// Convert a number from decimal to other base
class NumberConversion
{
    //Get valid value
    func actual_value(_ num: Int) -> String
    {
        var result  = "";
        
        if (num >= 0 && num <= 9)
        {
            result=String(UnicodeScalar(UInt8( num + Int(UnicodeScalar("0")!.value ))));
        }
        else
        {
           
           result = String(UnicodeScalar(UInt8((num - 10) + Int(UnicodeScalar("A")!.value ))));
        }
        
         return result;
        
    }
    //Convert decimal number in given base number
    func decimal_to_other(_ decimal : Int, _ base : Int)
    {
        var decimal_number = decimal;
        let destination_base = base;
        print("\n Decimal Number   : ", decimal_number, terminator: "");
        print("\n Destination Base : ", destination_base, terminator: "");
        var flag: Bool = false;
        if (decimal_number < 0)
        {
            decimal_number = -decimal_number;
            flag = true;
        }
        //This is used to store result
        var result: String = "";
        //Transform decimal to other base
        while (decimal_number > 0)
        {
            result = (self.actual_value(decimal_number % destination_base)) + result;
            decimal_number = decimal_number / destination_base;
        }
        if (flag == true)
        {
            result = "-" + result;
        }
        //Display result
        print("\n Result : ", result ,"\n", terminator: "");
    }
}
func main()
{

    let obj: NumberConversion = NumberConversion();
    //Test case
    
    obj.decimal_to_other(55, 2);
    obj.decimal_to_other(125, 16);
    obj.decimal_to_other(125, 8);
    obj.decimal_to_other(-28, 16);
    obj.decimal_to_other(24, 4);
    obj.decimal_to_other(2124, 16);

}
main();

Output

 Decimal Number   :  55
 Destination Base :  2
 Result :  110111

 Decimal Number   :  125
 Destination Base :  16
 Result :  7D

 Decimal Number   :  125
 Destination Base :  8
 Result :  175

 Decimal Number   :  -28
 Destination Base :  16
 Result :  -1C

 Decimal Number   :  24
 Destination Base :  4
 Result :  120

 Decimal Number   :  2124
 Destination Base :  16
 Result :  84C

Output Explanation

The provided code includes several test cases to demonstrate the functionality of the "decimal_to_other()" method. The output for each test case is explained below:


	Decimal Number   : 55
	Destination Base : 2
	Result : 110111

The decimal number 55 is converted to binary (base 2) as 110111.


	Decimal Number   : 125
	Destination Base : 16
	Result : 7D

The decimal number 125 is converted to hexadecimal (base 16) as 7D.


	Decimal Number   : 125
	Destination Base : 8
	Result : 175

The decimal number 125 is converted to octal (base 8) as 175.


	Decimal Number   : -28
	Destination Base : 16
	Result : -1C

The negative decimal number -28 is converted to hexadecimal (base 16) as -1C.


	Decimal Number   : 24
	Destination Base : 4
	Result : 120

The decimal number 24 is converted to quaternary (base 4) as 120.


	Decimal Number   : 2124
	Destination Base : 16
	Result : 84C

The decimal number 2124 is converted to hexadecimal (base 16) as 84C.

Time Complexity

The time complexity of the given algorithm to convert a decimal number to another base is O(logB(N)), where B is the destination base and N is the decimal number.

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment