How to print binary numbers digit by digit in javascript?

时间:2017-08-04 12:35:47

标签: javascript

Say I have a binary number in javascript:

var myNumber = 0b0001110;

How do I print it digit by digit? It would output this:

0
0
0
1
1
1
0

I tried to console String(myNumber).charAt(n) , with n being a given position, but it didn't work, also I don't want it to be converted to string. I want the decimal digits 0 and 1.
I'm asking for a way to print the numbers, but my ultimate goal here is to have access to them.

1 个答案:

答案 0 :(得分:0)

You just need to convert the number to a string and then loop over the characters:

var myNumber = 0b0001110;
var myString = myNumber.toString(2);

for(var x = 0; x < myString .length; x++){
  console.log(myString [x]);
}