decodeHex
Decodes a hex-encoded string into a regular string.
1/**
2 * Decodes a hex-encoded string into a regular string.
3 *
4 * @param hex - The hex string to decode.
5 * @returns Decoded string or null if input is invalid.
6 */
7export function decodeHex(hex: string): string | null {
8 try {
9 if (hex.length % 2 !== 0 || /[^0-9a-f]/i.test(hex)) {
10 return null;
11 }
12
13 const bytes = new Uint8Array(hex.length / 2);
14 for (let i = 0; i < hex.length; i += 2) {
15 bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);
16 }
17
18 return new TextDecoder().decode(bytes);
19 } catch {
20 return null;
21 }
22}
Validates Hex Input
Includes strict checks for even length and valid hex characters before attempting to decode.
Safe Failure Handling
Returns
null
for malformed input instead of throwing, ensuring safe usage in untrusted contexts.Unicode-Aware Decoding
Uses
TextDecoder
for proper decoding of UTF-8 characters, including multibyte sequences.Efficient Byte Construction
Converts hex to bytes directly using typed arrays, optimizing performance for large strings.
Tests | Examples
1test('decodeHex - decodes ASCII string', () => {
2 expect(decodeHex('48656c6c6f')).toBe('Hello');
3});
4
5test('decodeHex - decodes Unicode string', () => {
6 expect(decodeHex('d09fd180d0b8d0b2d0b5d182')).toBe('Привет');
7});
8
9test('decodeHex - empty string returns empty', () => {
10 expect(decodeHex('')).toBe('');
11});
12
13test('decodeHex - invalid hex returns null (odd length)', () => {
14 expect(decodeHex('123')).toBeNull();
15});
16
17test('decodeHex - invalid hex returns null (bad chars)', () => {
18 expect(decodeHex('zzzz')).toBeNull();
19});
Common Use Cases
Reading Encoded Data from Storage
Decode hex-encoded strings stored in localStorage or transmitted over the network.
Interpreting Hex-Formatted Payloads
Parse values from low-level APIs, hardware integrations, or binary protocols.
Crypto and Hash Processing
Convert hash values (e.g. SHA-256) from hex to readable formats for verification.
Log File or Debugging Tools
Decode hex dumps in developer tools or internal diagnostics for inspection.