From 1fe582663b7d21c9a2714a5f8114dfdb00eddb51 Mon Sep 17 00:00:00 2001 From: n loewen Date: Tue, 29 Aug 2023 20:30:53 -0400 Subject: [PATCH] conversions - Create `conversions.js` and move `hex2num` et al. out of `logging.js` --- src/conversions.js | 48 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 src/conversions.js diff --git a/src/conversions.js b/src/conversions.js new file mode 100644 index 0000000..f6e9f88 --- /dev/null +++ b/src/conversions.js @@ -0,0 +1,48 @@ +/** + * @param {number} num + * @returns {string} + */ +const num2hex = (num) => num.toString(16).toUpperCase().padStart(2, "0"); + +/** + * @param {string} hex + * @returns {number} + */ +const hex2num = (hex) => parseInt(hex, 16); + +/** + * Convert a number to binary, padded to 8 bits + * See here for an explanation: https://stackoverflow.com/questions/9939760/how-do-i-convert-an-integer-to-binary-in-javascript + * @param {number} num + * @returns {string} binary representation of the input + **/ +const num2bin = (num) => (num >>> 0).toString(2).padStart(8, "0"); + +/** + * Convert a number to binary, padded to 4 bits + * See here for an explanation: https://stackoverflow.com/questions/9939760/how-do-i-convert-an-integer-to-binary-in-javascript + * @param {number} num + * @returns {string} binary representation of the input + **/ +const num2bin_4bit = (num) => (num >>> 0).toString(2).padStart(4, "0"); + +/** + * @param {string} bin + * @returns {number} + */ +const bin2num = (bin) => parseInt(bin, 2) + +/** + * @param {Boolean} bool + * @returns {0|1} + **/ +const bool2bit = (bool) => bool ? 1 : 0; + +module.exports = { + "num2hex": num2hex, + "hex2num": hex2num, + "num2bin": num2bin, + "num2bin_4bit": num2bin_4bit, + "bin2num": bin2num, + "bool2bit": bool2bit, +} \ No newline at end of file