This C# program demonstrates how to convert between different number bases in C#. Specifically, there are built-in functions in C# that allow programmers to convert between the following: binary, octal, decimal, and hexadecimal.
The first part uses the parse method to convert to values from hexadecimal and decimal strings. The parse method only converts from base 10 and base 16, but it has more functionality.
The second part uses the Convert.ToString() function to convert an unsigned integer value uiN to convert to a string that contains a number in each of the given four bases.
The third part uses the Convert.ToUInt32() function to convert each one of four strings, one from each number base, to an unsigned integer value.
using System; namespace XoaX { class Program { static void Main(string[] args) { Console.WriteLine("Parsing strings:"); // Parse a decimal value string sDecP = "29.415"; double dP = double.Parse(sDecP, System.Globalization.NumberStyles.Number); Console.WriteLine("The double " + dP + " was parsed from " + sDecP + "."); // Parse a hexadecimal integer value string sHexP = "5f3a"; uint uiP = uint.Parse(sHexP, System.Globalization.NumberStyles.HexNumber); Console.WriteLine("The uint " + uiP + " was parsed from " + sHexP + "."); Console.WriteLine(); // Conversions to strings Console.WriteLine("Conversion to strings:"); uint uiN = 847; string sBinary = Convert.ToString(uiN, 2); Console.WriteLine("N = " + sBinary + " in binary."); string sOctal = Convert.ToString(uiN, 8); Console.WriteLine("N = " + sOctal + " in octal."); string sDecimal = Convert.ToString(uiN, 10); Console.WriteLine("N = " + sDecimal + " in decimal."); string sHexadecimal = Convert.ToString(uiN, 16); Console.WriteLine("N = " + sHexadecimal + " in hexadecimal."); Console.WriteLine(); // Conversion from strings Console.WriteLine("Conversion from strings:"); string sBinC = "1011011"; uint uiC = Convert.ToUInt32(sBinC, 2); Console.WriteLine(sBinC + " converted to " + uiC + " in decimal."); string sOctC = "1472"; uiC = Convert.ToUInt32(sOctC, 8); Console.WriteLine(sOctC + " converted to " + uiC + " in decimal."); string sDecC = "936"; uiC = Convert.ToUInt32(sDecC, 10); Console.WriteLine(sDecC + " converted to " + uiC + " in decimal."); string sHexC = "a5f"; uiC = Convert.ToUInt32(sHexC, 16); Console.WriteLine(sHexC + " converted to " + uiC + " in decimal."); } } }
Parsing strings: The double 29.415 was parsed from 29.415. The uint 24378 was parsed from 5f3a. Conversion to strings: N = 1101001111 in binary. N = 1517 in octal. N = 847 in decimal. N = 34f in hexadecimal. Conversion from strings: 1011011 converted to 91 in decimal. 1472 converted to 826 in decimal. 936 converted to 936 in decimal. a5f converted to 2655 in decimal. Press any key to continue . . .
© 20072025 XoaX.net LLC. All rights reserved.