Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

encodeHex

Encodes a string into a hexadecimal representation.

TypeScript
Copied!
1/**
2 * Encodes a string into a hexadecimal representation.
3 *
4 * @param str - The input string.
5 * @returns A hex-encoded string.
6 */
7export function encodeHex(str: string): string {
8  return Array.from(str)
9    .map(char => char.charCodeAt(0).toString(16).padStart(2, '0'))
10    .join('');
11}
  • Simple and Transparent Logic

    Uses native string and character methods, making the implementation easy to understand and maintain.

  • Consistent Output

    Pads each byte to two hexadecimal digits, ensuring uniform and predictable output length.

  • Cross-Environment Compatibility

    Relies only on built-in JavaScript features, making it safe for both browser and Node.js environments.

  • Byte-Level Precision

    Operates directly on character codes, giving fine-grained control over byte representation.

Tests | Examples

TypeScript
Copied!
1test('encodeHex - encodes ASCII text', () => {
2  expect(encodeHex('Hello')).toBe('48656c6c6f');
3});
4
5test('encodeHex - encodes empty string', () => {
6  expect(encodeHex('')).toBe('');
7});
8
9test('encodeHex - encodes numbers in string', () => {
10  expect(encodeHex('123')).toBe('313233');
11});
12
13test('encodeHex - encodes special characters', () => {
14  expect(encodeHex('!@#')).toBe('214023');
15});
16
17test('encodeHex - encodes Unicode characters', () => {
18  expect(encodeHex('Пр')).toBe('41f041f0'); // Cyrillic characters
19});

Common Use Cases

  • Data Encoding for Transmission

    Encode strings for low-level protocols or binary-safe transport layers.

  • Checksum or Hash Display

    Represent binary hash outputs (e.g., SHA, MD5) in human-readable hexadecimal form.

  • Debugging and Inspection

    Visualize the binary content of strings during debugging or logging.

  • Custom Serialization

    Store or transfer data in a compact and standardized format for custom protocols or embedded systems.

Codebase: Utilities -> Encoding -> encodeHex | Yevhen Klymentiev