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

后端 未结 3 2012
野趣味
野趣味 2020-12-05 02:15

Can anybody give me a little advice please?

I have a string, for example \"01001011\" and what I need to do is to reverse it, so I used .split(\'\') tha

3条回答
  •  遥遥无期
    2020-12-05 02:39

    Just call parseInt with a different radix, in this case use 2 for binary.

    var a = parseInt("01001011", 2);
    // a === 75
    

    parseInt attempts to figure out the radix itself when you don't explicitly specify it. From the Mozilla Developer Network:

    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).

    In this case, it is crucial that you do specify the radix, as otherwise it may be interpreted as either a decimal or an octal number. As a rule of thumb, always specify the radix.

提交回复
热议问题