Convert binary number to decimal and decimal to binary
As a computer science student at the university, you'll spend countless of hours of understandning binary numbers, hexa decimals and octal decimals. When it comes to the real life as a software engineer, it might not be super common to work with these numbers, especially if you are working on a high level language like JavaScript, Java, C# and so on. But that doesn't mean it can't be fun to dust of some knowledge and play around with these numbers.
So, in this tutorial, we will create two functions for converting decimal numbers to their binary representation and then the other way around.
What is a binary number?
First, let's briefly just explain what a binary number is. A binary number is a number that is expressed in the base-2 numeral system, where we only use 1 and 0. For example, let's take the number 2, in binary it will be 10. The first digit, in this scenario the 0 will be worth 1 and the next one will be worth 2 and the third 4 and so on. For the number 2, we will need two digits from the binary system, where the 1 will be worth 2 and then the last digit is not needed to be worth anything, hence the 0. For the number 3, the binary representation will be 11, where the left 1 will be worth 2 and the right 1 will be worth 1 (2+1 = 3).
I hope you followed, otherwise you can read more on e.g Wikipedia.
Convert binary to decimal
Let's start with creating a function for converting binary to decimal. We will create a function, that will accept a string with our binary number, and then we will return the decimal value.
We will start by defining our function.
const toDecimal = (binary) => {};
Next, we will declare our variables. We will need a variable for the current bitValue and our decimal representation.
let bitValue = 1, decimal = 0;
We initiate the bitValue with 1, since that is where we will start, and our decimal value will be initiated with 0.
To make it easier to calculate, we will reverse our binary string, and start with counting from right to left, meaning starting from bit value 1.
const reversedBinary = binary.split("").reverse().join("");
Note that this reverse function is not recommended for special characters and more complex strings, we have a guide on a more robust solution for reversing strings in JavaScript. But for this guide, this approach works fine.
Lastly, we will loop through each digit in the string, and add the current bit value to our decimal variable accordingly. So if we encounter a 1 we will add the current bit value to the decimal value, and then when we are done, we will return the decimal value.
Full function will look like this:
const toDecimal = (binary) => { let bitValue = 1, decimal = 0; const reversedBinary = binary.split("").reverse().join(""); for (let bit of reversedBinary) { if (bit === "1") { decimal += bitValue; } bitValue = bitValue * 2; } return decimal; };
And if we run some tests, it would look like this:
console.log(toDecimal("11")); // 3 console.log(toDecimal("1101")); // 13 console.log(toDecimal("11010")); // 26
Convert decimal to binary
Let's do the opposite. We will create a function, called toBinary that will accept a number and then we will figure out the binary representation and return it as a string.
This function will require some more code, but it is not necessary harder to grasp. Our first task is to calculate the highest bit value needed. So 1, 2, 4, 8 and so one. So if we have the number 7, our highest bit value would be 4 for example.
const toBinary = (decimal) => { let bitValue = 1; for (let i = 0; i < decimal; i++) { if (bitValue > decimal) { // Divide by two since our bitValue is larger than the decimal, and we want to start with 1 in our binary representation bitValue = bitValue / 2; break; } else if (bitValue === decimal) { // If the decimal number is equal to the bitValue, we just break the loop and use the bitValue as is. break; } bitValue *= 2; } };
When we have our bit value calculated, we will loop through and assign our 1 or 0 to the string. For each iteration in the loop, we will substract the bit value from the decimal number and divide the bitValue with 2 until we hit 0.
let binary = ""; while (bitValue > 0) { const bit = bitValue > decimal ? "0" : "1"; if (bit === "1") { decimal -= bitValue; } binary += bit; bitValue = Math.floor(bitValue / 2); } return binary;
Note that we use Math.floor in order to get our bitValue down to 0, otherwise we would end up in an infinite loop since the value will never hit 0 if we divide with 2.
Full function will look like this:
const toBinary = (decimal) => { let bitValue = 1; for (let i = 0; i < decimal; i++) { if (bitValue > decimal) { bitValue = bitValue / 2; break; } else if (bitValue === decimal) { break; } bitValue *= 2; } let binary = ""; while (bitValue > 0) { const bit = bitValue > decimal ? "0" : "1"; if (bit === "1") { decimal -= bitValue; } binary += bit; bitValue = Math.floor(bitValue / 2); } return binary; };
And to test it, we will run some example numbers:
console.log(toBinary(12)); // 1100 console.log(toBinary(24)); // 11000 console.log(toBinary(6)); // 110
And that's it!
Summary
In this tutorial, we showed how to convert numbers between binary and decimal. I hope you enjoyed this tutorial, and that it could help you with your project.
Did you solve it in another way? Hit us up with an e-mail on our contact page.
Have a great day!