TheAlgorithms/Go · error
invalid hexadecimal string
Error message
invalid hexadecimal string
What it means
hexToDecimal validates the (prefix-stripped) string against ^[0-9A-Fa-f]+$; characters outside the hex alphabet — including signs, spaces, underscores, or a lone "0x" — cause rejection before parsing begins.
Source
Thrown at conversion/hexadecimaltodecimal.go:38
var isValidHexadecimal = regexp.MustCompile("^[0-9A-Fa-f]+$").MatchString
// hexToDecimal converts a hexadecimal string to a decimal integer.
func hexToDecimal(hexStr string) (int64, error) {
hexStr = strings.TrimSpace(hexStr)
if len(hexStr) == 0 {
return 0, fmt.Errorf("input string is empty")
}
// Check if the string has a valid hexadecimal prefix
if len(hexStr) > 2 && (hexStr[:2] == "0x" || hexStr[:2] == "0X") {
hexStr = hexStr[2:]
}
// Validate the hexadecimal string
if !isValidHexadecimal(hexStr) {
return 0, fmt.Errorf("invalid hexadecimal string")
}
var decimalValue int64
for _, char := range hexStr {
var digit int64
if char >= '0' && char <= '9' {
digit = int64(char - '0')
} else if char >= 'A' && char <= 'F' {
digit = int64(char - 'A' + 10)
} else if char >= 'a' && char <= 'f' {
digit = int64(char - 'a' + 10)
} else {
return 0, fmt.Errorf("invalid character in hexadecimal string: %c", char)
}
decimalValue = decimalValue*16 + digit
}
return decimalValue, nilView on GitHub (pinned to 5ba447ec5f)
Solutions
- Sanitize/normalize input: trim, strip 0x/0X prefix, uppercase
- Use strconv.ParseInt(s, 16, 64) for standard parsing and error reporting
- Show the invalid string to the user for correction
Defensive patterns
Strategy: validation
When it happens
Trigger: Thrown at conversion/hexadecimaltodecimal.go:38 when the library encounters an invalid state.
Common situations: See trigger scenarios.
AI-assisted analysis of TheAlgorithms/Go@5ba447ec5f (2026-09-02).
Data as JSON: /api/errors/dad4b5a108d310b2.
Report an issue: GitHub.