The System.FormatException: Invalid hexadecimal string error in C# occurs when the program tries to convert a string to a numeric value but the string does not represent a valid hexadecimal number. Hexadecimal numbers are often used to represent binary data in a more human-readable format, but if the string is incorrectly formatted, the exception will be thrown.
Common Causes:
- Invalid Characters in the Hex String A valid hexadecimal string can only contain the characters
0-9
andA-F
(ora-f
for lowercase). If the string contains any character outside of these valid hexadecimal characters, aFormatException
will occur. Example:string hexString = "1G2H"; // Invalid characters 'G' and 'H' int number = Convert.ToInt32(hexString, 16); // Throws FormatException
Fix: Ensure that the string contains only valid hexadecimal characters (0-9
,A-F
). - Empty or Null String If the string is empty or null, attempting to convert it into a hexadecimal value will throw a
FormatException
. Example:string hexString = ""; // Empty string int number = Convert.ToInt32(hexString, 16); // Throws FormatException
Fix: Always check for empty or null strings before attempting conversion. - Incorrect Length for Hexadecimal Representation While the length of the string is not strictly defined, in some cases, the length of the string might not be appropriate for the expected value, especially when converting hexadecimal to a fixed-size type (e.g.,
byte
,int
, etc.). Example:string hexString = "1Z"; // Invalid hexadecimal string, contains 'Z' int number = Convert.ToInt32(hexString, 16); // Throws FormatException
Fix: Validate the string for its proper hexadecimal structure before performing conversion. - Leading or Trailing Spaces If the hexadecimal string contains leading or trailing spaces, it may still throw a
FormatException
, depending on the conversion method used. Example:string hexString = " 1A "; // Contains leading and trailing spaces int number = Convert.ToInt32(hexString, 16); // Throws FormatException
Fix: Trim spaces before attempting conversion:string hexString = " 1A "; int number = Convert.ToInt32(hexString.Trim(), 16); // Successful conversion
- Improper Prefix or Format Some libraries, such as
Convert.ToInt32()
, expect a specific format (e.g., without0x
prefix). If the string includes an incorrect prefix, such as0x
in some scenarios, it may result in aFormatException
. Example:string hexString = "0x1A"; // Incorrect format if no prefix is expected int number = Convert.ToInt32(hexString, 16); // Throws FormatException
Fix: Remove any unnecessary prefixes (like0x
) before performing the conversion:string hexString = "0x1A".Substring(2); // Removes '0x' int number = Convert.ToInt32(hexString, 16); // Successful conversion
How to Fix:
- Ensure Valid Hexadecimal Characters Make sure the string contains only valid hexadecimal characters (
0-9
,A-F
,a-f
). Example:string hexString = "1A2B"; int number = Convert.ToInt32(hexString, 16); // Successful conversion
- Check for Null or Empty Strings Before converting, always ensure that the string is not null or empty. Example:
string hexString = "1A"; if (!string.IsNullOrEmpty(hexString)) { int number = Convert.ToInt32(hexString, 16); // Successful conversion } else { Console.WriteLine("Invalid input string."); }
- Trim Leading/Trailing Whitespaces Use
Trim()
to remove leading and trailing spaces from the string before conversion. Example:string hexString = " 1A "; int number = Convert.ToInt32(hexString.Trim(), 16); // Successful conversion
- Handle Incorrect Prefixes If the string has a prefix like
0x
, remove it before conversion. Example:string hexString = "0x1A"; hexString = hexString.StartsWith("0x") ? hexString.Substring(2) : hexString; int number = Convert.ToInt32(hexString, 16); // Successful conversion
- Validate Hex String Before Conversion If you are not sure about the validity of the hexadecimal string, you can validate it using a regular expression. Example:
string hexString = "1A2B"; if (System.Text.RegularExpressions.Regex.IsMatch(hexString, @"^[0-9A-Fa-f]+$")) { int number = Convert.ToInt32(hexString, 16); // Successful conversion } else { Console.WriteLine("Invalid hexadecimal string."); }
Example of Correct Usage:
using System;
class Program
{
static void Main()
{
try
{
string hexString = "1A2B";
int number = Convert.ToInt32(hexString, 16); // Converts hex string to integer
Console.WriteLine($"Hex string {hexString} is {number} in decimal.");
}
catch (FormatException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}