Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Converting decimal to binary or hex based on a condition in JavaScript
Problem
We need to write a JavaScript function that takes in a number n and converts it based on a condition:
- If a number is even, convert it to binary.
- If a number is odd, convert it to hex.
Solution
We can use JavaScript's toString() method with different radix values to perform the conversion. For binary conversion, we use radix 2, and for hexadecimal conversion, we use radix 16.
Example
Here's the implementation:
const num = 1457;
const conditionalConvert = (num = 1) => {
const isEven = num % 2 === 0;
const toBinary = () => num.toString(2);
const toHexadecimal = () => num.toString(16);
return isEven
? toBinary()
: toHexadecimal();
};
console.log(conditionalConvert(num));
5b1
How It Works
The function works by:
-
Checking even/odd: Using the modulo operator
num % 2 === 0 -
Binary conversion:
num.toString(2)converts to base-2 -
Hex conversion:
num.toString(16)converts to base-16 - Conditional return: Using ternary operator for clean logic
Testing Different Values
// Test with even numbers (should return binary)
console.log("Even number 8:", conditionalConvert(8));
console.log("Even number 16:", conditionalConvert(16));
// Test with odd numbers (should return hex)
console.log("Odd number 15:", conditionalConvert(15));
console.log("Odd number 255:", conditionalConvert(255));
Even number 8: 1000 Even number 16: 10000 Odd number 15: f Odd number 255: ff
Simplified Version
Here's a more concise version of the same function:
const simpleConvert = (num) => {
return num % 2 === 0 ? num.toString(2) : num.toString(16);
};
console.log("Simple version - 1457:", simpleConvert(1457));
console.log("Simple version - 20:", simpleConvert(20));
Simple version - 1457: 5b1 Simple version - 20: 10100
Conclusion
Using JavaScript's toString() method with different radix values provides an elegant solution for conditional number base conversion. The modulo operator effectively determines whether to convert to binary or hexadecimal format.
Advertisements
