Stack is undoubtedly the best choice and the best place to reflect the advantages of stack for the conversion between hexadecimal systems in digital systems.
The following is a simple conversion between decimal numbers to 2, 8, and 16 in C:
(Of course, CLR also has a simpler method, that isConvert.Tostring(IntValue,IntTobase), value is the decimal number to be converted, tobase is the hexadecimal type to be converted, 2, 8 or 16)
Namespace Crldemo
{
Class Program
{
Static Void Main ( String [] ARGs)
{
Try
{
Numbersystemutil. convertdecimal (31, Scale. hexadecimal );
//Console. writeline (convert. tostring (31, 16 ));
}
Catch (Exception ex)
{
Console. writeline (ex. Message );
}
Finally
{
Console. Readline ();
}
}
}
Public Class Numbersystemutil
{
Public Static Void Convertdecimal ( Int Dec, scale)
{
Stack < Int > Stack = New Stack < Int > ();
While (Dec > 0 )
{
Stack. Push (Dec%(Int) Scale );
Dec=Dec/(Int) Scale;
}
While (Stack. Count > 0 )
{
If (Scale = Scale. hexadecimal)
Console. Write (stack. Pop (). tostring ( " X " ));
Else
Console. Write (stack. Pop ());
}
}
}
Public Enum Scale
{
Hexadecimal= 16,
Octal= 8,
Binary= 2
}
}