How to get the hexadecimal equivalent of a character in C#

Overview

We can use the HexEscape() method of the Uri class to get the hexadecimal equivalent of a character in C#. This method returns a string that is the hexadecimal equivalent of the given character.

Syntax

Uri.HexEscape(character)
Syntax of the HexEscape() method

Parameter value

character: This is the character whose hexadecimal equivalent we want to obtain.

Return value

The HexEscape() method returns a string, which is the hexadecimal equivalent of the specified character.

Example

using System;
class HelloWorld
{
static void Main()
{
// create and initialize some characters
char c1 = 'A';
char c2 = 'C';
char c3 = 'e';
char c4 = 'a';
// print hexadecimal equivalents of characters
Console.WriteLine(Uri.HexEscape(c1));
Console.WriteLine(Uri.HexEscape(c2));
Console.WriteLine(Uri.HexEscape(c3));
Console.WriteLine(Uri.HexEscape(c4));
}
}

Explanation

  • Lines 7–10: We declare and initialize some character variables.
  • Lines 13–16: We get the hexadecimal equivalents of the given characters using the HexEscape() method of the Uri class. Then, we print the results to the console.

Note: When we specify a character that is greater than 255, we get the ArgumentOutOfRangeException error. This error is thrown when the range of values that are acceptable for a particular method is exceeded.

Free Resources