How to convert binary representation of number from string to integer number in JavaScript?

If you want to convert the array back to a string use join() (MDN) and for converting a string to an integer use parseInt() (MDN). The second argument of the later is an optional radix.

JavaScript will try to determine, what radix to use, but to be sure you should always add your radix manually. Citing from MDN:

If radix is undefined or 0, JavaScript assumes the following:

  • If the input string begins with “0x” or “0X”, radix is 16 (hexadecimal).

  • If the input string begins with “0”, radix is eight (octal). This feature is non-standard, and some implementations deliberately do not support it (instead using the radix 10). For this reason always specify a radix when using parseInt.

  • If the input string begins with any other value, the radix is 10 (decimal).

So in your case the following code should work:

var a="01001011";

var b = parseInt( a.split('').reverse().join(''), 2 );

or just (if you would want to convert the starting string, without the reversal):

var b = parseInt( a, 2 );

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)