UNPKG

1.57 kBJavaScriptView Raw
1// Copyright 2017-2022 @polkadot/util authors & contributors
2// SPDX-License-Identifier: Apache-2.0
3const U8 = new Array(256);
4const U16 = new Array(256 * 256);
5
6for (let n = 0; n < 256; n++) {
7 U8[n] = n.toString(16).padStart(2, '0');
8}
9
10for (let i = 0; i < 256; i++) {
11 const s = i << 8;
12
13 for (let j = 0; j < 256; j++) {
14 U16[s | j] = U8[i] + U8[j];
15 }
16}
17/** @internal */
18
19
20function hex(value) {
21 const mod = value.length % 2;
22 const length = value.length - mod;
23 const dv = new DataView(value.buffer, value.byteOffset);
24 let result = '';
25
26 for (let i = 0; i < length; i += 2) {
27 // we only use getUint16 here instead of getUint32 - at least in our
28 // tests this is faster to execute (both long & short strings tested)
29 result += U16[dv.getUint16(i)];
30 }
31
32 if (mod) {
33 result += U8[dv.getUint8(length)];
34 }
35
36 return result;
37}
38/**
39 * @name u8aToHex
40 * @summary Creates a hex string from a Uint8Array object.
41 * @description
42 * `UInt8Array` input values return the actual hex string. `null` or `undefined` values returns an `0x` string.
43 * @example
44 * <BR>
45 *
46 * ```javascript
47 * import { u8aToHex } from '@polkadot/util';
48 *
49 * u8aToHex(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0xf])); // 0x68656c0f
50 * ```
51 */
52
53
54export function u8aToHex(value, bitLength = -1, isPrefixed = true) {
55 const length = Math.ceil(bitLength / 8);
56 return `${isPrefixed ? '0x' : ''}${!value || !value.length ? '' : bitLength > 0 && value.length > length ? `${hex(value.subarray(0, length / 2))}…${hex(value.subarray(value.length - length / 2))}` : hex(value)}`;
57}
\No newline at end of file