cardiograph-computer/javascript-old/conversions.js

48 lines
1.2 KiB
JavaScript

/**
* @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,
}