Created
October 20, 2014 14:05
-
-
Save sergeevabc/246dff8b8d3d6f106c38 to your computer and use it in GitHub Desktop.
Base16 array to hex
This file contains 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
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