From 1d83bab27d7050f9e20eb23d9ce7f14d4b366505 Mon Sep 17 00:00:00 2001 From: arobsn <87387688+arobsn@users.noreply.github.com> Date: Wed, 13 Sep 2023 18:14:13 -0300 Subject: [PATCH] add char code based hexToBytes function --- src/abstract/utils.ts | 31 +++++++++++++++++++++++++------ 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/src/abstract/utils.ts b/src/abstract/utils.ts index ff5b0c4..2682f2f 100644 --- a/src/abstract/utils.ts +++ b/src/abstract/utils.ts @@ -44,6 +44,27 @@ export function hexToNumber(hex: string): bigint { return BigInt(hex === '' ? '0' : `0x${hex}`); } +const enum HexCharCode { + ZERO = 48, // 0 + NINE = 57, // 9 + A_UP = 65, // A + F_UP = 70, // F + A_LO = 97, // a + F_LO = 102, // f +} + +function charCodeToBase16(char: number) { + if (char >= HexCharCode.ZERO && char <= HexCharCode.NINE) { + return char - HexCharCode.ZERO; + } else if (char >= HexCharCode.A_UP && char <= HexCharCode.F_UP) { + return char - (HexCharCode.A_UP - 10); + } else if (char >= HexCharCode.A_LO && char <= HexCharCode.F_LO) { + return char - (HexCharCode.A_LO - 10); + } + + throw new Error('Invalid byte sequence.'); +} + /** * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) */ @@ -52,12 +73,10 @@ export function hexToBytes(hex: string): Uint8Array { const len = hex.length; if (len % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + len); const array = new Uint8Array(len / 2); - for (let i = 0; i < array.length; i++) { - const j = i * 2; - const hexByte = hex.slice(j, j + 2); - const byte = Number.parseInt(hexByte, 16); - if (Number.isNaN(byte) || byte < 0) throw new Error('Invalid byte sequence'); - array[i] = byte; + for (let i = 0, j = 0, l = array.length; i < l; i++) { + const n1 = charCodeToBase16(hex.charCodeAt(j++)); + const n2 = charCodeToBase16(hex.charCodeAt(j++)); + array[i] = n1 * 16 + n2; } return array; }