UNPKG

@ethersphere/swarm-cli

Version:
42 lines (40 loc) 1.2 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.stripHexPrefix = stripHexPrefix; exports.hexToBytes = hexToBytes; exports.bytesToHex = bytesToHex; /** * Strips the '0x' hex prefix from a string * @param hex string input */ function stripHexPrefix(hex) { return hex.startsWith('0x') ? hex.slice(2) : hex; } /** * Converts a hex string to Uint8Array * * @param hex string input */ function hexToBytes(hex) { const hexWithoutPrefix = stripHexPrefix(hex); const bytes = new Uint8Array(hexWithoutPrefix.length / 2); for (let i = 0; i < bytes.length; i++) { const hexByte = hexWithoutPrefix.substr(i * 2, 2); bytes[i] = parseInt(hexByte, 16); } return bytes; } /** * Converts array of number or Uint8Array to hex string. * * Optionally provides a the '0x' prefix. * * @param bytes The input array * @param withPrefix Provides '0x' prefix when true (default: false) */ function bytesToHex(bytes, withPrefix = false) { const prefix = withPrefix ? '0x' : ''; const hexByte = (n) => n.toString(16).padStart(2, '0'); const hex = Array.from(bytes, hexByte).join(''); return `${prefix}${hex}`; }