How to Convert a Decimal Number to Binary in Javascript?

Share

To convert a decimal number to a binary number using Javascript, we use the function toString of the number type. This function takes a single argument, the radix, which refers to the base of the number used to produce the text string. In the case of binary numbers, the base is 2. Thus, the code would be:

const inDecimal_Number = 255;
const inBinary_String = inDecimal_Number.toString(2);
console.assert(inBinary_String === '11111111');

Note that we're talking about the function Number.toString(radix), which only exists in variables of the type number. To convert a string from decimal to a string in binary, it's necessary to first convert the input to a number using the function parseInt for integer numbers or parseFloat for rational numbers.

const inDecimal_String = '255';
const inDecimal_Number = parseInt(inDecimal_String);
const inBinary_String = inDecimal_Number.toString(2);
console.assert(inBinary_String === '11111111');

To convert a value without using a variable, it's necessary to use parentheses, since the dot (.) is ambiguous between a decimal separator (e.g. 3.14) and the member access operator (Number.toString);

const inBinary_String = (255).toString(2); // correct
const inBinary2_String = 255.toString(2); // syntax error

Note that either way the returned value is of type string, that is, text, it's a text representation of a value as binary number. There is no such thing as a binary number type in Javascript. However, there is a way to use numbers written in binary format directly through the prefix 0b.

const inBinary_Number = 0b11111111;
console.assert(inBinary_Number === 255);

Since the arithmetic is the same for both decimal numbers and binary ones, it's also possible to use this code in additions, subtractions, etc.

console.assert(0b1000 + 0b1000 === 16);
console.assert(0b1000 * 2 === 16);
console.assert(0b1000 * 0b10 === 16);

Comments

Leave a Reply

Leave your thoughts! Required fields are marked *