Hexadecimal and decimal number conversion in C#
In programming, it is often necessary to convert numbers between different bases. A common conversion is between hexadecimal (base 16) and decimal (base 10). Here's how to perform this conversion in C#:
Convert decimal to hexadecimal
To convert a decimal number to its hexadecimal representation, use the ToString("X")
method:
<code class="language-csharp">string hexValue = decimalValue.ToString("X");</code>
This converts decimalValue
to a hexadecimal string, where each number represents a value from 0 to 15 (for values 10-15, use A-F).
Convert hexadecimal to decimal
To convert a hexadecimal number to a decimal number, there are two methods:
int.Parse()
:<code class="language-csharp">int decimalValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);</code>
This method parses the hexValue
string into a hexadecimal number and returns an integer value.
Convert.ToInt32()
:<code class="language-csharp">int decimalValue = Convert.ToInt32(hexValue, 16);</code>
This method is equivalent to the above method, but uses the Convert
class to perform the conversion. The second parameter specifies base 16 for hexadecimal conversion.
The above is the detailed content of How to Convert Between Decimal and Hexadecimal Numbers in C#?. For more information, please follow other related articles on the PHP Chinese website!