Skip to content

Instantly share code, notes, and snippets.

@don
Created May 3, 2018 17:54
Show Gist options
  • Select an option

  • Save don/871170d88cf6b9007f7663fdbc23fe09 to your computer and use it in GitHub Desktop.

Select an option

Save don/871170d88cf6b9007f7663fdbc23fe09 to your computer and use it in GitHub Desktop.
Convert hex string to ArrayBuffer
/**
* Convert a hex string to an ArrayBuffer.
*
* @param {string} hexString - hex representation of bytes
* @return {ArrayBuffer} - The bytes in an ArrayBuffer.
*/
function hexStringToArrayBuffer(hexString) {
// remove the leading 0x
hexString = hexString.replace(/^0x/, '');
// ensure even number of characters
if (hexString.length % 2 != 0) {
console.log('WARNING: expecting an even number of characters in the hexString');
}
// check for some non-hex characters
var bad = hexString.match(/[G-Z\s]/i);
if (bad) {
console.log('WARNING: found non-hex characters', bad);
}
// split the string into pairs of octets
var pairs = hexString.match(/[\dA-F]{2}/gi);
// convert the octets to integers
var integers = pairs.map(function(s) {
return parseInt(s, 16);
});
var array = new Uint8Array(integers);
console.log(array);
return array.buffer;
}
@gjtiquia
Copy link
Copy Markdown

gjtiquia commented May 7, 2024

this works great thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment