UNPKG

1.64 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.u8aToHex = void 0;
4const U8 = new Array(256);
5const U16 = new Array(256 * 256);
6for (let n = 0; n < 256; n++) {
7 U8[n] = n.toString(16).padStart(2, '0');
8}
9for (let i = 0; i < 256; i++) {
10 const s = i << 8;
11 for (let j = 0; j < 256; j++) {
12 U16[s | j] = U8[i] + U8[j];
13 }
14}
15/** @internal */
16function hex(value, result) {
17 const mod = (value.length % 2) | 0;
18 const length = (value.length - mod) | 0;
19 for (let i = 0; i < length; i += 2) {
20 result += U16[(value[i] << 8) | value[i + 1]];
21 }
22 if (mod) {
23 result += U8[value[length] | 0];
24 }
25 return result;
26}
27/**
28 * @name u8aToHex
29 * @summary Creates a hex string from a Uint8Array object.
30 * @description
31 * `UInt8Array` input values return the actual hex string. `null` or `undefined` values returns an `0x` string.
32 * @example
33 * <BR>
34 *
35 * ```javascript
36 * import { u8aToHex } from '@polkadot/util';
37 *
38 * u8aToHex(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0xf])); // 0x68656c0f
39 * ```
40 */
41function u8aToHex(value, bitLength = -1, isPrefixed = true) {
42 // this is not 100% correct sinmce we support isPrefixed = false....
43 const empty = isPrefixed
44 ? '0x'
45 : '';
46 if (!value?.length) {
47 return empty;
48 }
49 else if (bitLength > 0) {
50 const length = Math.ceil(bitLength / 8);
51 if (value.length > length) {
52 return `${hex(value.subarray(0, length / 2), empty)}…${hex(value.subarray(value.length - length / 2), '')}`;
53 }
54 }
55 return hex(value, empty);
56}
57exports.u8aToHex = u8aToHex;