From 1e34b4487e6d76ef6d8b8b69e269490597321988 Mon Sep 17 00:00:00 2001 From: Vladimir Borovik Date: Wed, 31 Jul 2024 12:55:46 +0300 Subject: [PATCH] feat: add hexToUint8Array helper --- src/utils/hex-to-uint8-array.spec.ts | 9 +++++++++ src/utils/hex-to-uint8-array.ts | 18 ++++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 src/utils/hex-to-uint8-array.spec.ts create mode 100644 src/utils/hex-to-uint8-array.ts diff --git a/src/utils/hex-to-uint8-array.spec.ts b/src/utils/hex-to-uint8-array.spec.ts new file mode 100644 index 0000000..219ec7b --- /dev/null +++ b/src/utils/hex-to-uint8-array.spec.ts @@ -0,0 +1,9 @@ +import {hexToUint8Array} from './hex-to-uint8-array' + +describe('hexToUint8Array', () => { + it('should convert hex to Uint8Array', () => { + expect(hexToUint8Array('0xdeadbeef')).toEqual( + new Uint8Array([222, 173, 190, 239]) + ) + }) +}) diff --git a/src/utils/hex-to-uint8-array.ts b/src/utils/hex-to-uint8-array.ts new file mode 100644 index 0000000..deabbbb --- /dev/null +++ b/src/utils/hex-to-uint8-array.ts @@ -0,0 +1,18 @@ +import assert from 'assert' +import {trim0x} from './zero-x-prefix' +import {isHexBytes} from '../validations' + +/** + * Convert hex string to Uint8Array. String must be prefixed with 0x and have even length + */ +export const hexToUint8Array = (hex: string): Uint8Array => { + assert(isHexBytes(hex), 'invalid hex bytes') + const trimmed = trim0x(hex) + const array = new Uint8Array({length: trimmed.length / 2}) + + for (let i = 0; i < trimmed.length; i += 2) { + array[i / 2] = parseInt(trimmed.slice(i, i + 2), 16) + } + + return array +}