Created
May 3, 2018 17:54
-
-
Save don/871170d88cf6b9007f7663fdbc23fe09 to your computer and use it in GitHub Desktop.
Convert hex string to ArrayBuffer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this works great thanks!