How to write a function to convert a number to binary string(base 2) , 8 and 16.
In this blog post, we will explore the process of converting a decimal number to its binary representation in different number bases using JavaScript. We'll dive into how tp convert a number to base 2 (binary), base 8 (octal), and base 16 (hexadecimal) using the "toString() method.
1. Function to convert a number to binary (base 2) in JavaScript.
Given an integer n, use the toString method to convert to a string and pass a 2 as a parameter representing binary to it to convert it to binary as shown below.
const convertToBinary (n) => {
console.log(n.toString(2));
};
The above code when called will console log the answer in binary, base 2.
Example: convertToBinary(189) will console log "10111101" which is 189 in binary.
2. Function to convert a number to octal (base 8) in JavaScript.
The same method is applied to base 8, the 2 is replaced with a 8 to represent octal base.
Example code below.
const convertToBinary (n) => {
console.log(n.toString(8));
};
The above code when call will console log the answer in octal, base 8.
Example: convertToOctal(189) will console log "275" which is 189 in octal.
3. Function to convert a number to Hexadecimal (base 16) in JavaScript.
Using the same method again the 8 is replaced with 16 to represent hexadecimal.
Example code.
const convertToBinary (n) => {
console.log(n.toString(16));
};
The above code when call will console log the answer in hexadecimal , base 16.
Example: convertToHexa(189) will console log "bd" which is 189 in hexadecimal.
Found this article helpful? leave a comment down below.
comments
Add a comment...
Kato Isa
September 20, 2023
Greate ....
Someone
July 02, 2023
Amazing post, keep it up