Parse a hex string with strtoul

How strtoul converts hex text to an unsigned integer: what it accepts, what it discards, how to check errors, and when to keep the original string.

The C library function strtoul turns a run of characters into an unsigned long. With base 16, it reads hexadecimal text such as "1A3F" or "0x1a3f" and returns the number those digits represent. This review covers three questions: whether that conversion fits your use, what it actually changes, and what goes wrong when the input was copied from somewhere else.

Is strtoul the right tool for your hex input?

It is a good fit when you need the numeric value of plain ASCII hex text in C, such as a command-line argument, a configuration field or a protocol token, and you are willing to check its error signals. Its main benefit is that it is standard and already handles an optional 0x or 0X prefix, mixed letter case and leading whitespace. It also reports exactly where parsing stopped.

The deciding tradeoff is that it is permissive by default. It skips leading whitespace, accepts a sign and converts a valid prefix while ignoring trailing junk, and it does none of this with a warning. In addition, the width of unsigned long differs between platforms. If you do not check the end pointer and errno, malformed input can quietly produce a plausible-looking number.

Keep the value as plain text instead of converting it when the string is an identifier rather than a quantity. Hashes, color codes, MAC addresses, UUID fragments and fixed-width register dumps are examples. For these values, leading zeros, length or letter case carry meaning, or the value may exceed 64 bits. Converting to an integer discards that formatting, and you cannot recover it from the number alone.

What the conversion actually changes

This is not a visual transformation. Nothing is reversed, mirrored or restyled, and the input string is left untouched because the function takes it as a const pointer. The change is in representation: a sequence of characters becomes a binary integer. Only the value survives. Any 0x prefix, the letter case, leading zeros and surrounding whitespace are gone. If you print the number back with a format such as %lx, you get lowercase digits with no padding unless the format string asks for them.

#include <stdlib.h>

unsigned long strtoul(const char *nptr, char **endptr, int base);

With base 16, the standard describes parsing as these steps:

  • Skip leading whitespace, as classified by isspace.
  • Accept an optional + or - sign.
  • Accept an optional 0x or 0X prefix.
  • Read the longest run of hex digits: 0-9, a-f, A-F.
  • Store the address of the first unconsumed character in *endptr, if endptr is not null.
  • If a minus sign was present, negate the result in unsigned arithmetic.
  • On overflow, return ULONG_MAX and set errno to ERANGE.
  • If no digits form a valid subject sequence, return 0 and set *endptr to the start of the input.

Base 0 is different from base 16. It auto-detects the base from the prefix: 0x selects hex, and a leading 0 selects octal. If the input is always hex, pass 16 explicitly. Otherwise a string like "0755" is read as octal.

The examples below follow from the standard's rules with base 16 and a 64-bit unsigned long. They are not output from a recorded test run, so confirm edge cases on your own toolchain.

Input | Returned value | Where *endptr points
"1A3F" | 6719 | end of string
" 0x1a3f" | 6719 | end of string
"ff zz" | 255 | the space before "zz"
"0x" | 0 | the "x" (only the "0" is consumed)
"zz" | 0 | start of input (no conversion)
"-1" | ULONG_MAX | end of string
"FFFFFFFFFFFFFFFFF" (17 F's) | ULONG_MAX, errno set to ERANGE | end of string

Several of these rows show why the return value alone is not enough. A result of 0 can mean the input was "0", or it can mean nothing was parsed. ULONG_MAX can be a genuine value or an overflow. The input "-1" succeeds and produces the largest unsigned value, with no error flag.

Checking the result

Strict parsing needs four checks. First, set errno to 0 before the call, because strtoul only ever sets it and never clears it. After the call, confirm that the end pointer moved, that it reached the terminating null, and that errno is not ERANGE. Rejecting a leading sign or whitespace has to be done separately, before the call. The function below accepts only an optional prefix followed by hex digits.

#include <ctype.h>
#include <errno.h>
#include <stdbool.h>
#include <stdlib.h>

/* Accepts an optional 0x/0X prefix followed by hex digits only.
   Rejects empty input, leading whitespace or sign, trailing junk and overflow. */
bool parse_hex(const char *s, unsigned long *out)
{
    char *end;

    if (s == NULL || !isxdigit((unsigned char)*s))
        return false;

    errno = 0;
    unsigned long v = strtoul(s, &end, 16);

    if (end == s || *end != '\0')
        return false;
    if (errno == ERANGE)
        return false;

    *out = v;
    return true;
}

The first-character test rejects " 1F", "-1" and "+1" before strtoul can accept them. A bare "0x" passes that test, but it is then rejected because parsing stops at the "x". If your format should tolerate surrounding whitespace, trim it explicitly so the rule is visible in your code rather than implied by the library.

Width and range

The C standard guarantees that unsigned long holds at least 32 bits. It is 32 bits on Windows and on 32-bit targets, and 64 bits on most 64-bit Linux and macOS systems. As a result, a nine-digit hex value parses on one machine and reports ERANGE on another. For values that must reach 64 bits portably, use strtoull, which returns unsigned long long and is at least 64 bits wide, or strtoumax from inttypes.h. Values wider than 64 bits need a big-integer library, or should stay as strings.

Copied and shared input

strtoul works on bytes and recognizes only the ASCII digits, the letters a-f and A-F, and x or X in the prefix. Text pasted from web pages, PDFs, word processors or chat apps can contain characters that look the same but are not. Common examples are fullwidth digits and letters, non-breaking spaces, zero-width spaces, the Unicode minus sign, and the mathematical alphanumeric symbols that "fancy font" generators use for styled text. In UTF-8, each of these is a multi-byte sequence that is not a hex digit, so parsing stops at that point.

How much damage this does depends on where the character sits. A lookalike in the middle of the string truncates the result, which strict end-pointer checking catches. A leading non-breaking or zero-width space typically causes a failed conversion: in the C locale, its bytes are not classified as whitespace and are not digits. The standard also allows implementations to accept additional forms in locales other than C, and isspace depends on the active locale. Do not rely on locale behavior to clean up input.

If your input may come from copy and paste, normalize it before parsing, or reject it with a message that names the offending position, which the end pointer already gives you. This review does not document which specific applications insert such characters into copied hex text. Treat that as something to test with your own sources, not as a known list.

The parsed integer has no visual form of its own, so readability and assistive-technology concerns apply only where you display a value. Keep the original string alongside the number for logs, error messages and anything shown to people. That string is the plain-text equivalent that preserves the user's formatting. No evidence was supplied on how particular screen readers announce hex strings, so that question is left open here.