Hex to Int in C#
Hex to Int in C#. Enter your value into Hex Input and the Hex to Int in C# tool instantly returns the Int Output plus the matching C# snippet. Use the pantone to hex converter to get a close hex equivalent when you only have a Pantone name like Pantone 186 C to work from.
string hex = "FF"; int value = Convert.ToInt32(hex, 16); // value == 255
Need hex to int in C# without a FormatException surprise? The short version: pass the hexadecimal string to Convert.ToInt32(value, 16) and you get back the decimal value as an integer. The rest of this guide shows when to prefer int.Parse or TryParse, how the 0x prefix changes things, and what happens when the number no longer fits.
Hex to Int in C#: Picking the Right Method
.NET gives you three everyday ways to turn a hex string into a number, and each one reacts differently to a prefix, stray whitespace and bad input. Choosing between them is mostly a question of how much you trust the text you are parsing. The fastest way to get the decimal character codes for a piece of text is to type it into the text to decimal converter.
- Convert.ToInt32(string, 16): the shortest route, and the only one of the three that accepts a leading
0xon its own. - int.Parse(string, NumberStyles.HexNumber): stricter, culture aware, and happy with surrounding white space.
- int.TryParse(...): never throws, so it suits user input and files you do not control.
Every example below uses the same running input, 7B2E, so you can compare the results directly. It is four hex digits, and its integer value is 31534.
Where does a hexadecimal string come from in real projects? Usually a configuration file, a log line or a protocol dump, where each of the hex literals arrives as text instead of a compiled constant. Whatever the source, validate the text before you trust it: a hexadecimal value that looks fine to a person can still hide a stray space or a missing digit. The same method choices carry over to other numeric types such as long and uint, because each type has its own parse overload and its own limits.
Convert Hexadecimal to Integer in C# with Convert.ToInt32
The Convert.ToInt32 overload takes the text plus a fromBase argument. Passing 16 tells the runtime to read base 16, so each character is one of the hex digits and the whole hexadecimal representation collapses into a single int. The fastest way to get the little-endian byte sequence for a decimal number is to enter it into the decimal to little endian hex converter.
string hex = "7B2E";
int value = Convert.ToInt32(hex, 16);
Console.WriteLine(value); // Output: 31534The call is case insensitive, so uppercase and lowercase digits are interchangeable: 7b2e and 7B2E return the same hexadecimal value, 31534, as an integer.
Handling the 0x prefix
Source code, debuggers and datasheets usually print a hex literal with a 0x prefix. Convert.ToInt32 understands that prefix when fromBase is 16, so no cleanup is required:
string prefixed = "0x2F8D0";
int address = Convert.ToInt32(prefixed, 16);
Console.WriteLine(address); // Output: 194768A leading #, as in web colours, is not accepted and raises an exception, so strip it first with Replace("#", "").
Why the second argument matters
Leave out the base and Convert.ToInt32("7B2E") tries to read plain decimal digits and fails. The overload is documented as ToInt32(String, Int32), and the base can only be 2, 8, 10 or 16, which makes it a quick way to move between number systems such as binary, octal and hex in the same line of code.
Hex String to Int with int.Parse and NumberStyles.HexNumber
When you want the parse to follow .NET number-style rules, call int.Parse with NumberStyles.HexNumber. It lives in System.Globalization, so add that namespace first. The overload you are calling is Parse(String, NumberStyles), and the string it receives must contain the digits only.
using System.Globalization;
string hexString = "D3F1";
int parsed = int.Parse(hexString, NumberStyles.HexNumber);
Console.WriteLine(parsed); // Output: 54257The flag name AllowHexSpecifier does the same job with fewer extras: HexNumber also lets leading and trailing white space through, while AllowHexSpecifier accepts the hex digits only.
The prefix difference
Unlike the Convert approach, int.Parse rejects 0x. Feeding it a prefixed input throws a FormatException, because the letter x is not one of the hexadecimal digits it expects. Remove the prefix, or use Convert.ToInt32 if the text may arrive in either shape.
Culture settings
Pass CultureInfo.InvariantCulture as the third argument when the same code runs on machines with different regional settings. For hexadecimal text the culture rarely changes the answer, but being explicit keeps the intent obvious to the next reader.
Safe Hex Value Conversion with TryParse
A tool that reads a hex input from a form, a config file or a network packet cannot assume the text is valid. TryParse returns a boolean instead of throwing, which makes it the best fit for safe conversion. The TryParse() call also turns a hexadecimal string to an int without a try/catch block around it, so a bad row in a spreadsheet export never stops the whole import.
string userInput = "4E7A";
if (int.TryParse(userInput, NumberStyles.HexNumber,
CultureInfo.InvariantCulture, out int result))
{
Console.WriteLine($"Converted: {result}"); // Converted: 20090
}
else
{
Console.WriteLine("Invalid hexadecimal format");
}Error handling and input validation
Good error handling starts before the call. Trim the text, reject empty values, and confirm that it only holds 0-9, A-F, a-f. A small regex such as ^[0-9A-Fa-f]+$ is enough for that input validation step, and it lets you return a clear message for an invalid hexadecimal format instead of a stack trace.
If you prefer exceptions, catch FormatException for bad characters and wrap it in an ArgumentException with the offending text, so the caller knows which value to fix. Either way, handle invalid input at the boundary where it enters your program.
Large Hex Values, Overflow and Negative Results
An int holds 32 bits, so the int range ends at int.MaxValue, which is 7FFFFFFF in hex. What happens beyond that point surprises many developers, because the behaviour depends on how many digits you pass.
- Up to eight digits: the runtime always returns a number, reading the top bit as a sign (two's complement).
- More than eight digits: an overflow exception is thrown.
int negative = Convert.ToInt32("9C4E1A07", 16);
Console.WriteLine(negative); // Output: -1672603129The same eight digits mean 2622364167 if you read them as unsigned, and that larger hexadecimal value simply cannot be stored in a signed 32-bit int. When that is what you want, use Convert.ToUInt32. For large hex values that need more than 32 bits, Convert.ToInt64 returns a long:
uint unsignedValue = Convert.ToUInt32("9C4E1A07", 16); // 2622364167
long wide = Convert.ToInt64("1B9F0C55A2", 16); // 118,... fits in a longSigned versus unsigned results
Bit patterns such as hardware registers and checksums are normally unsigned, so pick uint there and keep int for values that may be negative. Mixing the two is a classic source of off-by-a-sign bugs in low-level parsing code.
Hex Digits, Base-16 Place Values and the Math
Understanding the arithmetic helps you spot wrong output quickly. Every hex digit is worth a power of sixteen, so a base-16 number is just a weighted sum:
$$value = \sum_{i=0}^{n-1} d_i \times 16^{i}$$For 7B2E the digits are 7, 11 (B), 2 and 14 (E), which gives \(7 \times 16^{3} + 11 \times 16^{2} + 2 \times 16^{1} + 14 \times 16^{0}\). That is 28672 + 2816 + 32 + 14, or 31534, the same integer every method above returned.
The hex calculator idea works in reverse as well: dividing a decimal number by 16 repeatedly and reading the remainders gives the hex digits, which is what ToString("X") does with its X format specifier.
Related Conversions: Byte Array, Float and Color Codes
Parsing a single number is only one slice of hex to int work in everyday programming. The same ideas appear in a few neighbouring tasks.
Byte array to hexadecimal string
Going the other way, BitConverter turns a byte array into text, and Convert.ToHexString does it without the dashes on .NET 5 and later:
byte[] bytes = [0x3A, 0xC7, 0x05];
Console.WriteLine(BitConverter.ToString(bytes)); // 3A-C7-05
Console.WriteLine(Convert.ToHexString(bytes)); // 3AC705Hex to float
A hex pattern can also carry a float. Parse it as uint, then call BitConverter.GetBytes and BitConverter.ToSingle. The result depends on the machine's endian order, which matters for communication protocols and binary file formats.
Color codes and memory addresses
Two common uses are color codes and memory addresses. A colour such as #1B9F0C becomes the integer 1810188 once the hash is removed, and bitwise shifts then split that integer into its RGB channels. The hex-to-int step is the same Convert call as before, and the red channel is just the converted number shifted right by 16 bits:
int rgb = Convert.ToInt32("1B9F0C", 16);
int red = (rgb >> 16) & 0xFF; // 27A memory address printed with a 0x prefix goes through the identical call.
Testing and Performance Best Practices
For production code, a few habits keep conversions predictable. The best practices below apply to any hex-to-int conversion, from a cryptography key reader to a low-level programming register dump.
- Write unit testing cases for the edge cases: an empty string, a single digit,
7FFFFFFF,80000000and nine digits. Each test should assert both the converted number and the exception type, so a regression in either shows up at once. - Prefer
TryParsefor external input and reserve the throwing methods for values you generate yourself. - Normalise first: trim, remove the prefix, and fix the case once. A single normalising method keeps every conversion in the code base consistent, and the rule is easy to explain in a review.
- For batch conversion, parse in a loop with one compiled pattern, and measure performance before optimising, since a single call costs very little.
Whether you convert hex to int once at start-up or inside a loop over thousands of rows, a tiny helper wraps these rules in one place:
static bool TryHexToInt(string text, out int result)
{
text = text.Trim().Replace("0x", "");
return int.TryParse(text, NumberStyles.HexNumber,
CultureInfo.InvariantCulture, out result);
}If you want to double-check a result outside your editor, a hex calculator or a decimal converter is a fast second opinion for the binary, hex and integer forms of the same number.