Skip to content

Instantly share code, notes, and snippets.

@mdciotti
Created October 16, 2015 06:22
Show Gist options
  • Save mdciotti/bfee43222d0a4c3960b4 to your computer and use it in GitHub Desktop.
Save mdciotti/bfee43222d0a4c3960b4 to your computer and use it in GitHub Desktop.
Converts hexadecimal-formatted strings to numbers and back
Number.prototype.toHex = function (padSize) {
if (padSize == undefined) padsize = 1;
var hex = this.toString(16).toUpperCase();
while (padSize > hex.length) {
hex = "0" + hex;
}
return hex;
};
String.prototype.toHex = function () {
var bytes, n, len, charCode;
len = this.length;
bytes = [];
for (n = 0; n < len; n++) {
charCode = this.charCodeAt(n);
// limit to utf-8 visible characters
if (0x1F < charCode && charCode < 0x7F) bytes.push(charCode.toHex(2));
}
return bytes.join("");
};
var hex_checksum = function (hex) {
var pair, tc, lsb,
sum = 0,
h = [],
d = [];
if (typeof hex === "string") {
hex.replace(/^0x/i, "");
for (var i = 0, len = hex.length; i < len; i+=2) {
pair = hex.substr(i, 2);
h.push(pair);
dec = parseInt(pair, 16);
d.push(dec);
sum += dec;
}
} else if (typeof hex === "number") {
return;
} else {
return null;
}
//console.log(h);
//console.log(d);
//console.log("Sum of Pairs:", sum.toHex());
//tc = ~sum + 0x01;
tc = (sum ^ 0xFF) + 0x01;
//console.log("Two's Complement of sum of pairs:", tc.toHex());
lsb = tc & 0xFF;
//return lsb < 0x10 ? "0" + lsb.toHex() : lsb.toHex();
return lsb;
};
var makeHex = function (maxLen, memStart, data) {
var lines, lineData, byteCount, address;
maxLen = Math.abs(parseInt(maxLen));
memStart = Math.abs(parseInt(memStart));
data.replace(/^0x/i, "");
lines = [];
address = memStart;
if (data.length % 2) { console.error("Data should have an even number of characters."); return; }
while (data.length > 0) {
lineData = data.substr(0, 2 * maxLen);
byteCount = (lineData.length >> 1).toHex(2);
str = byteCount + address.toHex(4) + "00" + lineData;
lines.push(":" + str + hex_checksum(str).toHex(2));
data = data.substr(2 * maxLen);
address += maxLen;
}
lines.push(":00000001FF");
return lines.join("\n");
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment