TheAlgorithms/Go · error

invalid character in hexadecimal string:

Error message

invalid character in hexadecimal string: 

What it means

During the manual parse loop, hexToBinary checks each character against 0-9, A-F and a-f ranges; any other character raises this error with the offending character embedded. It catches single invalid characters that may have passed a weaker or absent upfront validation. The message includes the character via string(char).

Source

Thrown at conversion/hexadecimaltobinary.go:50

	// Check if the hexadecimal string is valid
	if !isValidHex(hex) {
		return "", errors.New("invalid hexadecimal string: " + hex)
	}

	// Parse the hexadecimal string to an integer
	var decimal int64
	for i := 0; i < len(hex); i++ {
		char := hex[i]
		var value int64
		if char >= '0' && char <= '9' {
			value = int64(char - '0')
		} else if char >= 'A' && char <= 'F' {
			value = int64(char - 'A' + 10)
		} else if char >= 'a' && char <= 'f' {
			value = int64(char - 'a' + 10)
		} else {
			return "", errors.New("invalid character in hexadecimal string: " + string(char))
		}
		decimal = decimal*16 + value
	}

	// Convert the integer to a binary string without using predefined functions
	var binaryBuilder strings.Builder
	if decimal == 0 {
		binaryBuilder.WriteString("0")
	} else {
		for decimal > 0 {
			bit := decimal % 2
			if bit == 0 {
				binaryBuilder.WriteString("0")
			} else {
				binaryBuilder.WriteString("1")
			}
			decimal = decimal / 2
		}

View on GitHub (pinned to 5ba447ec5f)

Solutions

  1. Sanitize the input: remove separators (":", "-", spaces) and validate each rune is in [0-9a-fA-F] before calling.
  2. Use a strict regexp ^[0-9a-fA-F]+$ check to reject bad characters upfront.
  3. Inspect the character named in the error to locate the corruption source in the input pipeline.

Example fix

// before
out, err := conversion.HexToBinary("1A-3F") // invalid character in hexadecimal string: -
// after
clean := strings.NewReplacer("-", "", ":", "", " ", "").Replace(raw)
out, err = conversion.HexToBinary(clean)
Defensive patterns

Strategy: validation

Validate before calling

var hexRe = regexp.MustCompile(`^[0-9a-fA-F]+$`)
func isCleanHex(s string) bool { return hexRe.MatchString(strings.Map(func(r rune) rune {
    if r == '-' || r == ':' || r == ' ' { return -1 }
    return r
}, s)) }

Try / catch

out, err := conversion.HexToBinary(hex)
if err != nil {
    if strings.HasPrefix(err.Error(), "invalid character in hexadecimal string:") {
        return fmt.Errorf("non-hex character found: %w", err)
    }
    return err
}

Prevention

When it happens

Trigger: A hex string containing an invalid character anywhere after position 0, e.g. "1A3G", "12 34" (space), "1A-3F" (dash), or non-ASCII lookalike characters from Unicode input.

Common situations: Hex strings assembled from byte-dump formats with separators, UUID strings with dashes, or data corrupted by encoding conversions (e.g. UTF-16 or smart quotes).

Understand the failure class

Related errors


AI-assisted analysis of TheAlgorithms/Go@5ba447ec5f (2026-09-02). Data as JSON: /api/errors/b913f2eae5747c83. Report an issue: GitHub.