How to convert a hexadecimal string to Uint8Array and back in JavaScript?
问题 I want to convert a hexadecimal string like bada55 into a Uint8Array and back again. 回答1: Vanilla JS: const fromHexString = hexString => new Uint8Array(hexString.match(/.{1,2}/g).map(byte => parseInt(byte, 16))); const toHexString = bytes => bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), ''); console.log(toHexString(new Uint8Array([0, 1, 2, 42, 100, 101, 102, 255]))) console.log(fromHexString('0001022a646566ff')) Note: this method always completes. If the length of the