UNPKG

@ethersphere/swarm-cli

Version:
43 lines (41 loc) 1.27 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.bytesToHex = exports.hexToBytes = exports.stripHexPrefix = void 0; /** * Strips the '0x' hex prefix from a string * @param hex string input */ function stripHexPrefix(hex) { return hex.startsWith('0x') ? hex.slice(2) : hex; } exports.stripHexPrefix = stripHexPrefix; /** * 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; } exports.hexToBytes = hexToBytes; /** * 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}`; } exports.bytesToHex = bytesToHex;