convert-hex
Version:
Convert to/from hex string and array of bytes
47 lines (37 loc) • 1.14 kB
JavaScript
!function(globals) {
var convertHex = {
bytesToHex: function(bytes) {
/*if (typeof bytes.byteLength != 'undefined') {
var newBytes = []
if (typeof bytes.buffer != 'undefined')
bytes = new DataView(bytes.buffer)
else
bytes = new DataView(bytes)
for (var i = 0; i < bytes.byteLength; ++i) {
newBytes.push(bytes.getUint8(i))
}
bytes = newBytes
}*/
return arrBytesToHex(bytes)
},
hexToBytes: function(hex) {
if (hex.length % 2 === 1) throw new Error("hexToBytes can't have a string with an odd number of characters.")
if (hex.indexOf('0x') === 0) hex = hex.slice(2)
return hex.match(/../g).map(function(x) { return parseInt(x,16) })
}
}
// PRIVATE
function arrBytesToHex(bytes) {
return bytes.map(function(x) { return padLeft(x.toString(16),2) }).join('')
}
function padLeft(orig, len) {
if (orig.length > len) return orig
return Array(len - orig.length + 1).join('0') + orig
}
if (typeof module !== 'undefined' && module.exports) { //CommonJS
module.exports = convertHex
} else {
globals.convertHex = convertHex
}
}(this);