Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Quickly convert Decimal to other bases in C#
Converting decimal numbers to other bases in C# can be efficiently accomplished using a Stack data structure. The stack naturally handles the reversal of digits that occurs during the conversion process, making it an ideal choice for base conversion algorithms.
How It Works
The conversion process involves repeatedly dividing the decimal number by the target base and storing the remainders. Since division produces digits in reverse order, a stack helps retrieve them in the correct sequence:
Divide the decimal number by the target base
Push the remainder onto the stack
Update the number to the quotient
Repeat until the number becomes zero
Pop all elements from the stack to get the result
Example - Converting to Binary (Base 2)
using System;
using System.Collections.Generic;
class Program {
public static void Main() {
int n = 45;
int baseNum = 2;
Stack<int> s = new Stack<int>();
Console.WriteLine("Converting " + n + " to base " + baseNum);
do {
s.Push(n % baseNum);
n /= baseNum;
} while (n != 0);
Console.Write("Result: ");
while (s.Count > 0) {
Console.Write(s.Pop());
}
Console.WriteLine();
}
}
The output of the above code is −
Converting 45 to base 2 Result: 101101
Example - Converting to Different Bases
using System;
using System.Collections.Generic;
class Program {
public static string ConvertToBase(int number, int baseNum) {
if (number == 0) return "0";
Stack<int> s = new Stack<int>();
while (number != 0) {
s.Push(number % baseNum);
number /= baseNum;
}
string result = "";
while (s.Count > 0) {
int digit = s.Pop();
if (digit
The output of the above code is −
Number: 255
Binary (Base 2): 11111111
Octal (Base 8): 377
Hexadecimal (Base 16): FF
Using Built-in Convert Methods
C# also provides built-in methods for common base conversions −
using System;
class Program {
public static void Main() {
int number = 45;
Console.WriteLine("Number: " + number);
Console.WriteLine("Binary: " + Convert.ToString(number, 2));
Console.WriteLine("Octal: " + Convert.ToString(number, 8));
Console.WriteLine("Hexadecimal: " + Convert.ToString(number, 16));
}
}
The output of the above code is −
Number: 45
Binary: 101101
Octal: 55
Hexadecimal: 2d
Conclusion
Using a Stack for decimal to base conversion provides an elegant solution that automatically handles digit reversal. While C# offers built-in Convert.ToString() methods for common bases, understanding the stack-based approach helps you implement custom base conversions and grasp the underlying algorithm.
