Conversion between Integer and Hexadecimal in C#
This post will discuss how to convert an integer to hexadecimal in C# and vice versa.
Convert an Integer to a Hexadecimal in C#
1. Convert.ToString()
method
The recommended approach is to use the built-in method Convert.ToString() for converting a signed integer value to its equivalent hexadecimal representation. This method is demonstrated below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; public class Example { public static void Main() { int value = 1000; int toBase = 16; string hex = Convert.ToString(value, toBase); Console.WriteLine(hex); } } /* Output: 3e8 */ |
2. Int32.ToString()
method
The Int32.ToString() method can be used to convert a numeric value to equivalent string representation using the specified format. The following example displays an Int32
value using standard numeric format specifiers for hexadecimal (i.e., X
or x
).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; public class Example { public static void Main() { int value = 1000; string specifier = "X"; string hex = value.ToString(specifier); Console.WriteLine(hex); } } /* Output: 3E8 */ |
3. String.Format()
method
The following code example demonstrates how to use the String.Format
to convert an integer to equivalent hexadecimal representation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; public class Example { public static void Main() { int num = 1000; string hex = String.Format("{0:X}", num); Console.WriteLine(hex); } } /* Output: 3E8 */ |
Convert a Hexadecimal to an Integer in C#
We can use any of the following methods to convert the hexadecimal string to an integer in C#.
1. Int32.Parse()
method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; public class Example { public static void Main() { string hex = "3E8"; int value = Int32.Parse(hex, System.Globalization.NumberStyles.HexNumber); Console.WriteLine(value); } } /* Output: 1000 */ |
2. Convert.ToInt32()
method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; public class Example { public static void Main() { string hex = "3E8"; int value = Convert.ToInt32(hex, 16); Console.WriteLine(value); } } /* Output: 1000 */ |
That’s all about conversion between Integer and Hexadecimal in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)