Skip to content

Instantly share code, notes, and snippets.

@lanrion
Forked from tauzen/hexstring.js
Created March 23, 2020 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lanrion/ce66c0f7e71581e007b768fd27564b3f to your computer and use it in GitHub Desktop.
Save lanrion/ce66c0f7e71581e007b768fd27564b3f to your computer and use it in GitHub Desktop.
Hex string to byte and other way round conversion functions.
function byteToHexString(uint8arr) {
if (!uint8arr) {
return '';
}
var hexStr = '';
for (var i = 0; i < uint8arr.length; i++) {
var hex = (uint8arr[i] & 0xff).toString(16);
hex = (hex.length === 1) ? '0' + hex : hex;
hexStr += hex;
}
return hexStr.toUpperCase();
}
function hexStringToByte(str) {
if (!str) {
return new Uint8Array();
}
var a = [];
for (var i = 0, len = str.length; i < len; i+=2) {
a.push(parseInt(str.substr(i,2),16));
}
return new Uint8Array(a);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment