I am trying to write a function that must convert a decimal number to binary and vice versa.
The function receives two arguments:
- number, either binary/decimal
- conversion to perform
Works fine when I pass binaryDecimal(5, 2); (// prints 101) for decimal to binary conversation.
When I pass the arguments to the function to convert binary to decimal, it does not print anything.
const binarioDecimal = (number = 0, base = 0) => { // 0 by default if the user does not pass any value
if (number === 0 || base === 0) {
console.log(0);
} else if (typeof number === "number" && typeof base === "number") {
if (base === 2) {
let num = number;
let binary = (num % 2).toString();
for (; num > 1; ) {
num = parseInt(num / 2);
binary = (num % 2) + binary;
}
console.log(binary);
}
} else if (typeof number === "number" && typeof base === "number") {
//this is where i think the function fails
if (base === 10) {
var decimal = 0,
i = 0,
resto;
while (number !== 0) {
resto = number % 10;
number = Number.parseInt(number / 10);
decimal = decimal + resto * Math.pow(2, i);
++i;
}
console.log(decimal);
}
}
};
binarioDecimal(); // 0
binarioDecimal(23, 2); // 10111
binarioDecimal(101, 10); //does not print anything :(