Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
634 views
in Technique[技术] by (71.8m points)

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

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('') than .reverse() and now I need to read the array as a string and convert it to integer. Is it possible?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...