TheAlgorithms/JavaScript · error · Error
Argument is not a valid HEX code!
Error message
Argument is not a valid HEX code!
What it means
Thrown by hexToBinary when hexString contains any character that is not a hex digit. The regex /[^\da-f]/gi allows only 0-9 and a-f/A-F; anything else (spaces, 0x prefix, 'g'-'z', punctuation) triggers it. Note this is a plain Error, not a TypeError, because the type is correct but the content is invalid.
Source
Thrown at Conversions/HexToBinary.js:27
6: '0110',
7: '0111',
8: '1000',
9: '1001',
a: '1010',
b: '1011',
c: '1100',
d: '1101',
e: '1110',
f: '1111'
})[key.toLowerCase()] // select the binary number by valid hex key with the help javascript object
const hexToBinary = (hexString) => {
if (typeof hexString !== 'string') {
throw new TypeError('Argument is not a string type')
}
if (/[^\da-f]/gi.test(hexString)) {
throw new Error('Argument is not a valid HEX code!')
}
/*
Function for converting Hex to Binary
1. We convert every hexadecimal bit to 4 binary bits
2. Conversion goes by searching in the lookup table
*/
return hexString.replace(/[0-9a-f]/gi, (lexeme) => binLookup(lexeme))
}
export default hexToBinary
View on GitHub (pinned to 5c39e87a9a)
Solutions
- Strip prefixes/separators first: hexString.replace(/^0x/i, '').replace(/[^0-9a-f]/gi, '').
- Trim whitespace and newlines before calling.
- Validate with /^[0-9a-f]+$/i.test(input) and reject early with a clearer message.
Example fix
// before
hexToBinary('0xFF')
// after
hexToBinary('0xFF'.replace(/^0x/i, '')) Defensive patterns
Strategy: validation
Validate before calling
const clean = String(hexString).replace(/^0x/i, '').replace(/[^0-9a-f]/gi, '')
if (!clean) throw new Error('No valid hex digits')
return hexToBinary(clean) Type guard
const isValidHex = (s) => typeof s === 'string' && /^[0-9a-f]+$/i.test(s)
Try / catch
try {
hexToBinary(hexString)
} catch (e) {
if (/not a valid HEX code/.test(e.message)) {
return hexToBinary(hexString.replace(/^0x/i, '').trim())
}
throw e
} Prevention
- Strip '0x' prefixes and '#' before calling.
- Trim whitespace and newlines from pasted or file-read input.
- Pre-validate with /^[0-9a-f]+$/i and reject early.
When it happens
Trigger: Calling hexToBinary('0xFF') (the 'x' is invalid), hexToBinary('ff ff') (space), hexToBinary('gg'), or hexToBinary('#ffffff') (the '#' fails). Even a trailing newline will trip it.
Common situations: Input carries a '0x' prefix from a formatter; pasted values include spaces or a leading '#'; CRLF newlines from a file line; mixed notation like 'hFF'.
Related errors
- Invalid hex string.
- Duplicate characters in character set are not allowed
- Not a valid character: ${digit}
- Argument is not a string type
- Invalid units
AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13).
Data as JSON: /api/errors/e79595e918cdf402.
Report an issue: GitHub.