Quickly convert Decimal to other bases in C#


To quickly convert decimal to other bases, use Stacks. Let us see an example.

Firstly, I have set the variable “baseNum” as 2

int baseNum = 2;

In the same way, if you want another base, then −

// base 8
int baseNum = 8;

// base 10
int baseNum = 10;

After getting the value, set a stack and get the values by getting the remainder and other calculations as shown below.

Here, n is the decimal number.

Stack s = new Stack();
do {
   s.Push(n % baseNum);
   n /= baseNum;
} while (n != 0);

After using the stack, pop out the elements. That would give you the result.

Let’s say the number n is 45, then the result in binary i.e. base 2 would be −

Result...
101101

Updated on: 22-Jun-2020

450 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements