From 597fba2fd0a5edd318f8586b5e4a19078466d94b Mon Sep 17 00:00:00 2001 From: Andy Wang Date: Wed, 15 Jan 2020 00:14:43 +0000 Subject: [PATCH] Add line size formatting and comma separation --- src/core/lib/Hex.mjs | 35 ++++++++++++++++++++++++++--------- src/core/operations/ToHex.mjs | 13 ++++++++++++- 2 files changed, 38 insertions(+), 10 deletions(-) diff --git a/src/core/lib/Hex.mjs b/src/core/lib/Hex.mjs index 5ae06a7e..0274f876 100644 --- a/src/core/lib/Hex.mjs +++ b/src/core/lib/Hex.mjs @@ -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; + } } diff --git a/src/core/operations/ToHex.mjs b/src/core/operations/ToHex.mjs index 6ae48da9..b2712b40 100644 --- a/src/core/operations/ToHex.mjs +++ b/src/core/operations/ToHex.mjs @@ -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]); } /**