Uri.FromHex() Method in C#

The Uri.FromHex() method in C# converts a single hexadecimal digit character to its corresponding decimal integer value. This static method is part of the Uri class and is commonly used when working with URL encoding and decoding operations.

Syntax

Following is the syntax −

public static int FromHex(char digit);

Parameters

  • digit − A hexadecimal digit character (0-9, a-f, A-F) to convert to its decimal equivalent.

Return Value

Returns an int value representing the decimal equivalent of the hexadecimal digit. The method throws an ArgumentException if the character is not a valid hexadecimal digit.

Examples

Converting Hexadecimal Letters

The following example demonstrates converting hexadecimal letter characters to their decimal values −

using System;

public class Demo {
   public static void Main() {
      char ch = 'D';
      Console.WriteLine("Character value = " + ch);
      int res = Uri.FromHex(ch);
      Console.WriteLine("Converted int value = " + res);
   }
}

The output of the above code is −

Character value = D
Converted int value = 13

Converting Hexadecimal Numbers

This example shows how numeric hexadecimal digits are converted −

using System;

public class Demo {
   public static void Main() {
      char ch = '6';
      Console.WriteLine("Character value = " + ch);
      int res = Uri.FromHex(ch);
      Console.WriteLine("Result = " + res);
   }
}

The output of the above code is −

Character value = 6
Result = 6

Converting Multiple Hexadecimal Digits

The following example demonstrates converting various hexadecimal characters including both uppercase and lowercase letters −

using System;

public class Demo {
   public static void Main() {
      char[] hexChars = {'0', '9', 'A', 'F', 'a', 'f'};
      
      foreach (char ch in hexChars) {
         int decimal_value = Uri.FromHex(ch);
         Console.WriteLine("Hex '{0}' = Decimal {1}", ch, decimal_value);
      }
   }
}

The output of the above code is −

Hex '0' = Decimal 0
Hex '9' = Decimal 9
Hex 'A' = Decimal 10
Hex 'F' = Decimal 15
Hex 'a' = Decimal 10
Hex 'f' = Decimal 15

Common Use Cases

The Uri.FromHex() method is typically used in:

  • URL decoding operations where percent-encoded characters need to be converted back to their original form

  • Processing hexadecimal color codes in web applications

  • Converting hexadecimal strings to their numeric equivalents character by character

Conclusion

The Uri.FromHex() method provides a simple way to convert individual hexadecimal digit characters to their decimal integer equivalents. It accepts both uppercase and lowercase hexadecimal letters (A-F, a-f) and numeric digits (0-9), making it useful for URL processing and hexadecimal data conversion tasks.

Updated on: 2026-03-17T07:04:35+05:30

112 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements