From 4ba27ad4a7ab1c0915a19bc64636ba1fa5ddc296 Mon Sep 17 00:00:00 2001 From: Jeff Parsons Date: Thu, 23 Jul 2015 17:41:27 -0700 Subject: [PATCH] Include binary as an output option --- modules/pcjs/lib/debugger.js | 2 +- modules/shared/lib/strlib.js | 54 ++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/modules/pcjs/lib/debugger.js b/modules/pcjs/lib/debugger.js index b71db3878..1638cfe8d 100644 --- a/modules/pcjs/lib/debugger.js +++ b/modules/pcjs/lib/debugger.js @@ -4026,7 +4026,7 @@ if (DEBUGGER) { } if (!fError) { value = aVals.pop(); - if (fPrint) this.println(sExpOrig + "=" + value + " (" + str.toHexLong(value) + ")"); + if (fPrint) this.println(sExpOrig + "=" + str.toHex(value) + "h bin=" + str.toBinBytes(value) + " dec=" + value + '.'); } else { if (fPrint) this.println("error parsing '" + sExpOrig + "' at character " + (sExpOrig.length - sExp.length)); } diff --git a/modules/shared/lib/strlib.js b/modules/shared/lib/strlib.js index b7df14440..caeb04f4f 100644 --- a/modules/shared/lib/strlib.js +++ b/modules/shared/lib/strlib.js @@ -94,6 +94,60 @@ str.parseInt = function(s, base) return value; }; +/** + * toBin(n, cch) + * + * Converts an integer to binary, with the specified number of digits (up to the default of 32). + * + * @param {number|null|undefined} n is a 32-bit value + * @param {number} [cch] is the desired number of binary digits (32 is both the default and the maximum) + * @return {string} the binary representation of n + */ +str.toBin = function(n, cch) +{ + var s = ""; + if (cch === undefined) { + cch = 32; + s = "b"; + } else { + if (cch > 32) cch = 32; + } + /* + * An initial "falsey" check for null takes care of both null and undefined; + * we can't rely entirely on isNaN(), because isNaN(null) returns false, oddly enough. + */ + if (n == null || isNaN(n)) { + while (cch-- > 0) s = '?' + s; + } else { + while (cch-- > 0) { + s = ((n & 0x1)? '1' : '0') + s; + n >>= 1; + } + } + return s; +}; + +/** + * toBinBytes(n, cb) + * + * Converts an integer to binary, with the specified number of bytes (up to the default of 4). + * + * @param {number|null|undefined} n is a 32-bit value + * @param {number} [cb] is the desired number of binary bytes (4 is both the default and the maximum) + * @return {string} the binary representation of n + */ +str.toBinBytes = function(n, cb) +{ + var s = ""; + if (!cb || cb > 4) cb = 4; + for (var i = 0; i < cb; i++) { + if (s) s = ',' + s; + s = str.toBin(n & 0xff, 8) + 'b' + s; + n >>= 8; + } + return s; +}; + /** * toHex(n, cch) *