From f46266439a66adf7cb77122a5eb8fa252aa3df55 Mon Sep 17 00:00:00 2001 From: AJ ONeal Date: Fri, 6 Oct 2017 20:30:21 -0600 Subject: [PATCH] show ascii too --- bin/cli.js | 12 +++++++++--- hexdump.js | 19 +++++++++++++++++-- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/bin/cli.js b/bin/cli.js index 3ada1f7..4985da9 100755 --- a/bin/cli.js +++ b/bin/cli.js @@ -5,13 +5,19 @@ var hexdump = require('../').hexdump; var fsname = process.argv[2]; var fs = require('fs'); +var opts = {}; -if (!fsname || '--help' === fs || '-h' === fs) { - console.error('Usage: hexdump.js '); +if (!fsname || '--help' === fsname || '-h' === fsname) { + console.error('Usage: hexdump.js -C '); process.exit(2); return; } +if ('-C' === fsname) { + opts.C = true; + fsname = process.argv[3]; +} + try { fs.statSync(fsname); } catch(e) { @@ -21,7 +27,7 @@ try { } var nb = fs.readFileSync(fsname); -var str = hexdump(nb.buffer, nb.byteOffset, nb.byteLength); +var str = hexdump(nb.buffer, nb.byteOffset, nb.byteLength, opts); console.log(str); }()); diff --git a/hexdump.js b/hexdump.js index 918a880..41e8da2 100644 --- a/hexdump.js +++ b/hexdump.js @@ -1,7 +1,8 @@ (function (exports) { 'use strict'; -exports.hexdump = function hexdump(ab, offset, len) { +exports.hexdump = function hexdump(ab, offset, len, opts) { + if (!opts) { opts = {}; } var ui8 = new Uint8Array(ab.buffer || ab, offset || ab.byteOffset, len || ab.byteLength); var bytecount = 0; var head = ' 0 1 2 3 4 5 6 7 8 9 A B C D E F'; @@ -20,7 +21,21 @@ exports.hexdump = function hexdump(ab, offset, len) { lead = '0' + lead; } - return lead + ' ' + str; + while (str.length < 48) { + str += ' '; + } + + if (opts.C) { + return lead + ' ' + str + ' |' + str.replace(/ /g, '').match(/.{1,2}/g).map(function (ch) { + var c = String.fromCharCode(parseInt(ch, 16)); + if (!/[ -~]/.test(c)) { + c = '.'; + } + return c; + }).join('') + '|'; + } else { + return lead + ' ' + str; + } }).join('\n'); trail = (len || ab.byteLength).toString(16);