Convert number to binary

Convert number to binary
0.0 0

#1

I saw a solution of this challenge from codewar

The challenge instruction is as below:

Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition.

The binary number returned should be a string.

Here is the solution I saw on github:

function addBinary( a, b ){ var sum = a + b, binary = ''; while ( sum > 0 ) { binary = ( sum % 2 ) + binary; sum = Math.floor( sum / 2 ); } return binary; }
console.log( addBinary( 1,2 ) ); //Should be 11
console.log( addBinary( 51,12 ) ); //Should be 111111
console.log( addBinary( 100, 0 ) ); //Should be 1100100

My question is that since binary always start counting from right to left,
Why we don’t need to add anything to this code to change the binary order from right to left???

Will be very appreciate if there is anyone can explain to me.


#2

Because of this line. Each new digit is appended to the beginning of the string.

Note that JavaScript numbers natively support conversion to binary representations via the toString method:

(255).toString(); // "255" (default is radix 10)
(255).toString(2); // "11111111" (radix 2, i.e. binary)
(255).toString(16); // "ff" (radix 16, i.e. hexadecimal)

#3

I didn’t know this until you told me! Thank you vary much!!