user5178932
user5178932

Reputation:

Can anyone explain this process with converting decimal numbers to Binary

I have looked around the internet for a way to convert decimal numbers into binary numbers. and i found this piece of code in some forum.

var number = prompt("Type a number!") //Asks user to input a number
var converted = []; // creates an array with nothing in it

while(number>=1) { //While the number the user typed is over or equal to 1 its shoud loop
    converted.unshift(number%2); // takes the "number" and see if you can divid it by 2 and if theres any rest it puts a "1" otherwise "0"
    number = Math.floor(number/2); // Divides the number by 2, then starts over again
}

console.log(converted)

I'm not understanding everything completely, so i made some comments of what i think the pieces of code do. But anyone that can explain in more detail? or is the way i think the code does correct?

Upvotes: 0

Views: 106

Answers (2)

mchach24
mchach24

Reputation: 73

This code is based on a technique for converting decimal numbers to binary.

If I take a decimal number. I divide it by two and get the remainder which will either be 0 or 1. Once you divide 57 all the way down to 0. You get the binary number for example:

57 / 2 = 28 r 1; 28 / 2 = 14 r 0; 14 / 2 = 7 r 0; 7 / 2 = 3 r 1; 3 / 2 = 1 r 1; 1 / 2 = 0 r 1;

The remainders are the binary number. Sorry if it's a bit hard to read. I definitely recommend writing it out on paper. Read from the last remainder to the first, the remainders look like this: 111001

Reverse it to make it correct. array.unshift() can do this or you could use array.push() then array.reverse() after the while loop. Unshift() is probably a better approach.

57 in decimal is equal to 111001, which you can check.

BTW, this algorithm works for other bases, as long you are converting from decimal. Or at least as far as I know.

I hope this helped.

Upvotes: 1

Etheryte
Etheryte

Reputation: 25319

It seems like you've got the gist of it down.

Let's start with a random number:

6 ===  110b

Now let's see what the above method does:

The number is geq than 1, hence, let's add the last bit of the number to the output

6%2 === 0 //output [0]

the number we're working with after dividing the number by two, which is essentially just bit-shifting the whole thing to the right is now 11b (from the original 110b). 11b === 3, as you'd expect.

You can alternatively think of number % 2 as a bit-wise AND operation (number & 1):

  110
&   1
-----
    0

The rest of the loop simply carries the same operation out as long as needed: find the last bit of the current state, add it to the output, shift the current state.

Upvotes: 0

Related Questions