How to Convert a Binary Number to Decimal in Javascript?

Share

To convert a binary number to decima in Javascript, we use the function parseInt. This function has to arguments: the string of the text to be converted to number, and an argument called the radix, which means the base used to interpret the number. For binary numbers, the base is 2. If the radix isn't defined, its default value is 10, which is the base for decimal numbers. Thus, the code would be:

const inDecimal = parseInt('11111111', 2);
console.assert(inDecimal === 255);

The function parseInt returns NaN if it's not possible to convert the value. However, it doesn't return NaN if the value starts with a valid digit! That is, '$1' is invalid, but '1$' is valid. The function will convert all valid characters until the first invalid character in the string.

console.assert(isNaN(parseInt('', 2)));
console.assert(isNaN(parseInt('$', 2)));
console.assert(isNaN(parseInt('$1', 2)));
console.assert(parseInt('1$', 2) === 1);
console.assert(isNaN(parseInt('2', 2)));
console.assert(parseInt('12', 2) === 1);
console.assert(parseInt('100021', 2) === 8);
console.assert(parseInt(' \t 1000', 2) === 8);

As you can see, the string '100021' is converted to the number 8 because the function only converts characters before the first invalid character (the '2'), that is, the function only considered the characters '1000', which in binary equals 8. On the other hand, spaces including tabs ('\t') are ignored.

Although this seems terrible in terms of validation, it's important to remember that various CSS units have a suffix that isn't a digit. For example: '20px'. This function would return the value 20 in this case without you having to do anything special. Unfortunately that's not what we're using the function for this time, so we'll have to do something special.

To validate that the input is a binary number, the most practical way is to use a regex. We consider a string to be valid only if it has the characters '0' and '1' from start to end, that is:

/^[01]+$/

In Javascript:

const isValid = /^[01]+$/.test(input);
let inBinary = NaN;
if(isValid) {
    inBinary = parseInt(input, 2);
}

Observe that this regex will reject an input if it contains spaces. For a better user experience, it's a good idea to ignore spaces at the start and end of the input. The easiest way to do this is using the function trim() that returns a string without these spaces.

input = input.trim();
const isValid = /^[01]+$/.test(input);

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *