convert a number from base 2 to base 16 in csharp

To convert a number from base 2 to base 16 in C#, you can use the Convert.ToUInt32 method to convert the binary string to an unsigned 32-bit integer, and then call the .ToString method with a format string of "X" to convert it to a hexadecimal string.

main.cs
string binaryString = "10101010"; // binary number to convert
uint binaryNumber = Convert.ToUInt32(binaryString, 2); // convert binary string to uint
string hexString = binaryNumber.ToString("X"); // convert uint to hexadecimal string
Console.WriteLine(hexString); // output: "AA"
281 chars
5 lines

In this example, the binary string "10101010" is converted to an unsigned 32-bit integer using the Convert.ToUInt32 method. The 2 argument tells the method that the input string is in base 2. Next, the ToString method is called on the resulting uint with a format string of "X". The "X" format specifier tells ToString to output the number in hexadecimal format. Finally, the resulting hexadecimal string is output to the console.

gistlibby LogSnag