add char code based hexToBytes function

This commit is contained in:
arobsn 2023-09-13 18:14:13 -03:00
parent 4be208e4b2
commit 1d83bab27d
No known key found for this signature in database
GPG Key ID: C677FDCEA0BACA53

@ -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;
}