Home > Backend Development > C++ > How to Convert Between Decimal and Hexadecimal Numbers in C#?

How to Convert Between Decimal and Hexadecimal Numbers in C#?

Barbara Streisand
Release: 2025-01-26 03:06:10
Original
902 people have browsed it

How to Convert Between Decimal and Hexadecimal Numbers in C#?

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>
Copy after login

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:

  1. Use int.Parse():
<code class="language-csharp">int decimalValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);</code>
Copy after login

This method parses the hexValue string into a hexadecimal number and returns an integer value.

  1. Use Convert.ToInt32():
<code class="language-csharp">int decimalValue = Convert.ToInt32(hexValue, 16);</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template