C# - Number System - Conversion - Convert Decimal to any Base (Hexadecimal, Octal, Binary and any other)
This program converts a decimal number to any base. For example, convert from decimal to hexadecimal, convert from decimal to octal, convert from decimal to binary etc.
CODE
using System;
class Program
{
public static void Main(string[] args)
{
int inputNumber = 1234;
int baseToConvert = 16;
//call the function
string convertedNumber = ConvertDecimalToAnyBase(inputNumber, baseToConvert);
Console.WriteLine("Decimal Input: " + inputNumber);
Console.WriteLine("Base " + baseToConvert + " : " + convertedNumber);
Console.ReadKey();
}
static string ConvertDecimalToAnyBase(int decimalNumber, int baseToConvert)
{
string convertedNumber = "";
if (decimalNumber == 0)
//if the number is 0, return 0
convertedNumber = decimalNumber.ToString();
else
{
//the loop will iterate as long as decimalNumber > 0
//the value of decimalNumber will be changed inside the loop
while (decimalNumber > 0)
{
//get the remainder
int remainder = decimalNumber % baseToConvert;
//convert the remainder to its corresponding character
string remainderCharacter = "";
if (remainder >= 0 && remainder <= 9)
//if remainder is between 0 and 9, return the same
remainderCharacter = remainder.ToString();
else
{
//if remainder is greater than 9, convert as A, B etc
//ASCII 65 = A, 66 = B etc
//get the ASCII value using the expression below.
int asciiValue = remainder - 10 + 65;
//convert the ascii to its corresponding character
remainderCharacter = ((char)asciiValue).ToString();
}
//prefix the remainderCharacter to the result
convertedNumber = remainderCharacter + convertedNumber;
//get the quotient
decimalNumber = decimalNumber / baseToConvert;
}
}
return convertedNumber;
}
}
INPUT & OUTPUT
Comments
Post a Comment