UNPKG

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