}
static hexToBytes (hex: string): Bytes {
- const e = 'hex invalid'
- if (typeof hex !== 'string') return this.err(e)
- const hl = hex.length
- const al = hl / 2
- if (hl % 2) return this.err(e)
- const array = new Uint8Array(al)
- for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
- // treat each char as ASCII
- const n1 = this._char(hex.charCodeAt(hi)) // parse first char, multiply it by 16
- const n2 = this._char(hex.charCodeAt(hi + 1)) // parse second char
- if (n1 === undefined || n2 === undefined) return this.err(e)
- array[ai] = n1 * 16 + n2 // example: 'A9' => 10*16 + 9
- }
- return array
+ if (!/[0-9A-Fa-f]+/.test(hex ?? '')) return this.err('hex invalid')
+ if (hex.length % 2) hex = `0${hex}`
+ const intArray = hex.match(/.{2}/g)?.map(v => parseInt(v, 16))
+ return new Uint8Array(intArray ?? [])
}
// prettier-ignore