Here in this post, we are going to see how to convert Binary numbers to Decimal numbers.
To convert any Binary number to Decimal in JavaScript can be done in one single line. Yes, you heard right, there is a function available in JavaScript which will convert any number system to decimal and the function is,
parseInt(string, radix)
we all know that parseInt() can convert any string to integer right? but what most of us don’t know is that there is another optional parameter that we can pass in the function ie., radix, this parameter accepts values between 2 and 32 that represents the number system. Here is the list of number systems
Radix | Name |
2 | Binary numeral system |
8 | Octal system |
10 | Decimal system |
12 | Duodecimal system |
16 | Hexadecimal system |
20 | Vigesimal |
60 | Sexagesimal system |
So in our case, we need to use radix as “2” for converting Binary to Decimal.
For example,
1 2 3 |
var binNum = "1100"; var dec = parseInt(binNum, 2); alert(dec); |
the above script will give an alert 12 as the decimal value of binary number 1100 is 12.
The same if you want to convert any Hexadecimal value to a decimal number in JavaScript, it is so simple, let’s see another example:
1 2 3 |
var hexNum = "C"; var dec = parseInt(hexNum, 16); alert(dec); |
Here also you will get an alert 12 as the decimal value of Hexadecimal number C is 12
I hope you would have got an idea of how to convert any number system to decimal in pure JavaScript.