UNPKG

1.23 kBJavaScriptView Raw
1// Copyright 2017-2022 @polkadot/util authors & contributors
2// SPDX-License-Identifier: Apache-2.0
3import { U8_TO_HEX, U16_TO_HEX } from "../hex/alphabet.js";
4/** @internal */
5
6function hex(value) {
7 const mod = value.length % 2;
8 const length = value.length - mod;
9 const dv = new DataView(value.buffer, value.byteOffset);
10 let result = '';
11
12 for (let i = 0; i < length; i += 2) {
13 result += U16_TO_HEX[dv.getUint16(i)];
14 }
15
16 if (mod) {
17 result += U8_TO_HEX[dv.getUint8(length)];
18 }
19
20 return result;
21}
22/**
23 * @name u8aToHex
24 * @summary Creates a hex string from a Uint8Array object.
25 * @description
26 * `UInt8Array` input values return the actual hex string. `null` or `undefined` values returns an `0x` string.
27 * @example
28 * <BR>
29 *
30 * ```javascript
31 * import { u8aToHex } from '@polkadot/util';
32 *
33 * u8aToHex(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0xf])); // 0x68656c0f
34 * ```
35 */
36
37
38export function u8aToHex(value, bitLength = -1, isPrefixed = true) {
39 const length = Math.ceil(bitLength / 8);
40 return `${isPrefixed ? '0x' : ''}${!value || !value.length ? '' : length > 0 && value.length > length ? `${hex(value.subarray(0, length / 2))}…${hex(value.subarray(value.length - length / 2))}` : hex(value)}`;
41}
\No newline at end of file