toAscii && fromAscii moved to utils

This commit is contained in:
Marek Kotewicz
2015-01-31 13:54:39 +01:00
parent 0b82a05a75
commit 4bdf52fc1e
7 changed files with 123 additions and 147 deletions

View File

@@ -33,7 +33,49 @@ var findIndex = function (array, callback) {
return end ? i - 1 : -1;
};
module.exports = {
findIndex: findIndex
/// @returns ascii string representation of hex value prefixed with 0x
var toAscii = function(hex) {
// Find termination
var str = "";
var i = 0, l = hex.length;
if (hex.substring(0, 2) === '0x') {
i = 2;
}
for (; i < l; i+=2) {
var code = parseInt(hex.substr(i, 2), 16);
if (code === 0) {
break;
}
str += String.fromCharCode(code);
}
return str;
};
var toHex = function(str) {
var hex = "";
for(var i = 0; i < str.length; i++) {
var n = str.charCodeAt(i).toString(16);
hex += n.length < 2 ? '0' + n : n;
}
return hex;
};
/// @returns hex representation (prefixed by 0x) of ascii string
var fromAscii = function(str, pad) {
pad = pad === undefined ? 0 : pad;
var hex = toHex(str);
while (hex.length < pad*2)
hex += "00";
return "0x" + hex;
};
module.exports = {
findIndex: findIndex,
toAscii: toAscii,
fromAscii: fromAscii
};