Manipulating numerical data is fundamental to many applications. In some cases, we may need to convert numbers between different bases. This article explores different ways to convert a number between hexadecimal and decimal in C# while offering insights into the methods and scenarios where each shines.
Without further ado, let’s start!
Different Ways to Convert a Number From Decimal to Hexadecimal
We can use different C# methods and custom implementations to help us achieve our goal of converting a number from decimal to hexadecimal. Let’s have a look at some of them:
Convert Using ToString()
First, we can use the ToString()
method to convert a number from decimal to its hexadecimal equivalent:
return decimalVal.ToString("X");
.NET provides many useful standard format specifiers like “C” for currency, “E” for exponential (scientific) notation, “P” for percent, and for our purposes, “X” for hexadecimal. In our example, we call the ToString()
overload, which takes a format string parameter. We pass in “X” as the format string, indicating that our desired string format is hexadecimal.
Use string.Format() for Conversion
Similar to ToString()
, we can use string.Format()
to convert a number from decimal to hexadecimal in C#. The function works by inserting the value of our integer variables into another string, specifying “X” as the format, to convert it to hexadecimal:
return string.Format("{0:X}", decimalVal);
We can also achieve the same result with an interpolated string:
return $"{decimalVal:X}";
Now, let’s validate our implementation:
var result = _conversionExamples.DecimalToHexUsingStringFormat(decimalVal); Assert.IsNotNull(result); Assert.IsInstanceOfType(result, typeof(string)); Assert.AreEqual(hexVal, result);
Convert Decimal to Hexadecimal Using Bitwise Operations
Apart from string formatting, we can use bitwise operations to convert decimal numbers to hexadecimal:
public string DecimalToHexUsingBitwiseMethod(int decimalVal) { const int hexBaseOffset = 'A' - 0xA; var hexStringLength = (BitOperations.Log2((uint) decimalVal) >> 2) + 1; return string.Create(hexStringLength, decimalVal, (span, value) => { for (int i = span.Length - 1; i >= 0; i--) { var digit = (byte) (value & 0xF); span[i] = (char) (digit + (digit < 10 ? '0' : hexBaseOffset)); value >>= 4; } }); }
First, we define a constant for hexBaseOffset
as 'A' - 0xA
(uppercase hex output). Next, we calculate the length of the resulting hexadecimal string based on the equation length = Floor(Log16(decimalVal)) + 1
. Our code employs an equivalent calculation using the Base2 logarithm, followed by a right shift twice (equivalent to dividing by 4).
Once we have the length of the resultant hexadecimal string, we use string.Create()
it to build the hex string, computing each digit starting at the rightmost position (least significant digit) in the string and working left (most significant digit). For each char
we first perform a bitwise AND with 0xF
to zero all of the bits except the first 4 (one hex character).
Next, we convert it to a hex character using our hex offset. When it is less than 10, we simply add the offset for the char 0
to our value. When it is greater than 10, we use our hexBaseOffset
to compute the appropriate value from between 'A'
and 'F'
.
Our final step is to divide the decimal value by 16 (right shift four times)
How to Convert a Number From Hexadecimal to Decimal
Let’s learn some of the techniques we can use to convert hexadecimal to decimal numbers.
Convert Using int.Parse()
We can use the int.Parse()
method, which works by converting the hexadecimal string to its 32-bit signed integer equivalent:
return int.Parse(hexVal, System.Globalization.NumberStyles.HexNumber);
This method will throw exceptions if the input is not a valid hexadecimal string; TryParse()
is a good alternative in situations where the validity of the hexadecimal string may be uncertain.
Finally, we can use some tests to verify that our implementation returns valid results:
var result = _conversionExamples.HexToDecimalUsingParse(hexVal); Assert.IsNotNull(result); Assert.IsInstanceOfType(result, typeof(int)); Assert.AreEqual(decimalVal, result);
Convert.ToInt32() Technique
Besides parsing, we can use the static Convert.ToInt32()
method to convert hexadecimal values to their decimal equivalents. The method takes two arguments: the string to convert and the base of the string value:
return Convert.ToInt32(hexVal, 16);
It’s important to note that 2, 8, 10, and 16 are the only valid bases for Convert.ToInt32()
.
The Convert.ToInt32()
method can throw FormatException
and OverflowException
exceptions; therefore, we should always ensure we pass valid hexadecimal strings.
Let’s validate this method using int.MaxValue
value:
7FFFFFFF converted to decimal using Convert.Int32 is 2147483647
Performance Analysis
Let’s analyze how long each technique takes to perform the conversion:
| Method | decimalVal | hexVal | Mean | Median | Rank | Gen0 | Allocated | |------------------------------- |----------- |--------- |----------:|----------:|-----:|-------:|----------:| | DecimalToHexUsingBitwiseMethod | 2147483647 | ? | 23.72 ns | 23.58 ns | 1 | 0.0191 | 40 B | | DecimalToHexUsingToString | 2147483647 | ? | 27.92 ns | 27.66 ns | 2 | 0.0191 | 40 B | | DecimalToHexUsingStringFormat | 2147483647 | ? | 116.05 ns | 134.25 ns | 3 | 0.0305 | 64 B | | | | | | | | | | | HexToDecimalUsingParse | ? | 7FFFFFFF | 17.15 ns | 16.98 ns | 1 | - | - | | HexToDecimalUsingConvert | ? | 7FFFFFFF | 26.29 ns | 26.31 ns | 2 | - | - |
We can see that using the bitwise method is the fastest way to convert decimal numbers to their hexadecimal equivalents. However, we prefer the ToString()
solution for its simplicity and maintainability. While it is not significantly slower, ToString()
, due to its support of a variety of formatting options, has some additional complexity. On the other hand, the string.Format()
technique is close to four times as slow as the ToString()
technique.
When converting from hexadecimal to decimal numbers, we can see that using int.Parse()
is twice as fast as using Convert.ToInt32()
. Therefore, we highly recommend using the ToString() and int.Parse() methods due to their performance superiority.
Conclusion
In this article, we’ve explored various methods for converting numbers between hexadecimal and decimal formats in C#. We’ve covered some key techniques suitable for different scenarios, providing us with options depending on our project requirements. Which techniques have you used before, or do you have other preferred methods? Share your experiences and insights in the comments.