Home >Backend Development >C#.Net Tutorial >Quickly convert Decimal to other bases in C#

Quickly convert Decimal to other bases in C#

王林
王林forward
2023-08-27 09:41:051049browse

Quickly convert Decimal to other bases in C#

To quickly convert decimal to other bases, use the stack. Let's look at an example.

First, I set the variable "baseNum" to 2

int baseNum = 2;

Similarly, if you want another base, then -

// base 8
int baseNum = 8;

// base 10
int baseNum = 10;

After getting the value, set one Stack, the value is calculated by finding the remainder, as shown below.

Here, n is a decimal number.

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

After using the stack, pop the element. This will give you the results.

Assuming the number n is 45, then the binary result (i.e. in base 2) will be -

Result...
101101

The above is the detailed content of Quickly convert Decimal to other bases in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete