Add line size formatting and comma separation

This commit is contained in:
Andy Wang 2020-01-15 00:14:43 +00:00
parent f7be8d720b
commit 597fba2fd0
2 changed files with 38 additions and 10 deletions

View File

@ -23,25 +23,42 @@ import Utils from "../Utils.mjs";
*
* // returns "0a:14:1e"
* toHex([10,20,30], ":");
*
* // returns "0x0a,0x14,0x1e"
* toHex([10,20,30], "0x", 2, ",")
*/
export function toHex(data, delim=" ", padding=2) {
export function toHex(data, delim=" ", padding=2, extraDelim="", lineSize=0) {
if (!data) return "";
if (data instanceof ArrayBuffer) data = new Uint8Array(data);
let output = "";
const prepend = (delim === "0x" || delim === "\\x");
for (let i = 0; i < data.length; i++) {
output += data[i].toString(16).padStart(padding, "0") + delim;
const hex = data[i].toString(16).padStart(padding, "0");
if (prepend) {
output += delim + hex;
} else {
output += hex + delim;
}
if (extraDelim) {
output += extraDelim;
}
// Add LF after each lineSize amount of bytes but not at the end
if ((i !== data.length - 1) && ((i + 1) % lineSize === 0)) {
output += "\n";
}
}
// Add \x or 0x to beginning
if (delim === "0x") output = "0x" + output;
if (delim === "\\x") output = "\\x" + output;
if (delim.length)
return output.slice(0, -delim.length);
else
// Remove the extraDelim at the end (if there is);
// and remove the delim at the end, but if it's prepended there's nothing to remove
const rTruncLen = extraDelim.length + (prepend ? 0 : delim.length);
if (rTruncLen) {
// If rTruncLen === 0 then output.slice(0,0) will be returned, which is nothing
return output.slice(0, -rTruncLen);
} else {
return output;
}
}

View File

@ -30,6 +30,16 @@ class ToHex extends Operation {
name: "Delimiter",
type: "option",
value: TO_HEX_DELIM_OPTIONS
},
{
name: "Bytes per line",
type: "number",
value: 0
},
{
name: "Comma separated",
type: "boolean",
value: false
}
];
}
@ -41,7 +51,8 @@ class ToHex extends Operation {
*/
run(input, args) {
const delim = Utils.charRep(args[0] || "Space");
return toHex(new Uint8Array(input), delim, 2);
const comma = args[2] ? "," : "";
return toHex(new Uint8Array(input), delim, 2, comma, args[1]);
}
/**