Skip to content

Instantly share code, notes, and snippets.

@sergeevabc
Created October 20, 2014 14:05
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 sergeevabc/246dff8b8d3d6f106c38 to your computer and use it in GitHub Desktop.
Save sergeevabc/246dff8b8d3d6f106c38 to your computer and use it in GitHub Desktop.
Base16 array to hex
function Uint8Array2hex(arr) {
var hexEncodeArray = '0123456789abcdef'.split('');
var s = '';
for (var i = 0; i < arr.length; i++) {
var code = arr[i];
s += hexEncodeArray[code >>> 4];
s += hexEncodeArray[code & 0x0F];
}
return s;
}
// alternative 1
function bytesToHex(p) {
/** @const */
var enc = '0123456789abcdef'.split('');
var len = p.length,
arr = [],
i = 0;
for (; i < len; i++) {
arr.push(enc[(p[i]>>>4) & 15]);
arr.push(enc[(p[i]>>>0) & 15]);
}
return arr.join('');
}
// alternative 2
var hex = {
decode: function(text) {
return text.match(/.{2}/g).map(function(byte) {
return parseInt(byte, 16);
});
},
encode: function(bytes) {
var result = [];
for (var i = 0, hex; i < bytes.length; i++) {
hex = bytes[i].toString(16);
if (hex.length < 2) {
hex = '0' + hex;
}
result.push(hex);
}
return result.join('');
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment