I want to convert binary string in to digit E.g
var binary = "1101000" // code for 104
var digit = binary.toString(10); // Convert String or Digit (But it does not work !)
console.log(digit);
How is it possible? Thanks
I want to convert binary string in to digit E.g
var binary = "1101000" // code for 104
var digit = binary.toString(10); // Convert String or Digit (But it does not work !)
console.log(digit);
How is it possible? Thanks
The parseInt
function converts strings to numbers, and it takes a second argument specifying the base in which the string representation is:
var digit = parseInt(binary, 2);
ES6 supports binary numeric literals for integers, so if the binary string is immutable, as in the example code in the question, one could just type it in as it is with the prefix 0b
or 0B
:
var binary = 0b1101000; // code for 104
console.log(binary); // prints 104
var num = 10;
alert("Binary " + num.toString(2)); // 1010
alert("Octal " + num.toString(8)); // 12
alert("Hex " + num.toString(16)); // a
alert("Binary to Decimal " + parseInt("1010", 2)); // 10
alert("Octal to Decimal " + parseInt("12", 8)); // 10
alert("Hex to Decimal " + parseInt("a", 16)); // 10
parseInt()
with radix is a best solution (as was told by many):
But if you want to implement it without parseInt, here is an implementation:
function bin2dec(num){
return num.split('').reverse().reduce(function(x, y, i){
return (y === '1') ? x + Math.pow(2, i) : x;
}, 0);
}
I gathered all what others have suggested and created following function which has 3 arguments, the number and the base which that number has come from and the base which that number is going to be on:
changeBase(1101000, 2, 10) => 104
Run Code Snippet to try it yourself:
function changeBase(number, fromBase, toBase) {
if (fromBase == 10)
return (parseInt(number)).toString(toBase)
else if (toBase == 10)
return parseInt(number, fromBase);
else {
var numberInDecimal = parseInt(number, fromBase);
return parseInt(numberInDecimal).toString(toBase);
}
}
$("#btnConvert").click(function(){
var number = $("#txtNumber").val(),
fromBase = $("#txtFromBase").val(),
toBase = $("#txtToBase").val();
$("#lblResult").text(changeBase(number, fromBase, toBase));
});
#lblResult {
padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="txtNumber" type="text" placeholder="Number" />
<input id="txtFromBase" type="text" placeholder="From Base" />
<input id="txtToBase" type="text" placeholder="To Base" />
<input id="btnConvert" type="button" value="Convert" />
<span id="lblResult"></span>
<p>Examples: <br />
<em>110, 2, 10</em> => <em>6</em>; (110)<sub>2</sub> = 6<br />
<em>2d, 16, 10</em> => <em>45</em>; (2d)<sub>16</sub> = 45<br />
<em>45, 10, 16</em> => <em>2d</em>; 45 = (2d)<sub>16</sub><br />
<em>101101, 2, 16</em> => <em>2d</em>; (101101)<sub>2</sub> = (2d)<sub>16</sub>
</p>
FYI: If you want to pass 2d
as a hex number, you need to send it as a string so it goes like this:
changeBase('2d', 16, 10)
Building on the comments of @baptx, @Jon and @ikhvjs, the following should work with really large binary strings:
// ES10+
function bin2dec(binStr) {
const lastIndex = binStr.length - 1;
return Array.from(binStr).reduceRight((total, currValue, index) => (
(currValue === '1') ? total + (BigInt(2) ** BigInt(lastIndex - index)) : total
), BigInt(0));
}
Or, the same using a for
loop:
// ES10+
function bin2dec(binStr) {
const lastIndex = binStr.length - 1;
let total = BigInt(0);
for (let i = 0; i < binStr.length; i++) {
if (binStr[lastIndex - i] === '1') {
total += (BigInt(2) ** BigInt(i));
}
}
return total;
}
For example:
console.log(bin2dec('101')); // 5n
console.log(bin2dec('110101')); // 53n
console.log(bin2dec('11111111111111111111111111111111111111111111111111111')); // 9007199254740991n
console.log(bin2dec('101110110001101000111100001110001000101000101011001100000011101')); // 6741077324010461213n
Wrote a blog post about it for those who wish to learn more.
function binaryToDecimal(string) {
let decimal = +0;
let bits = +1;
for(let i = 0; i < string.length; i++) {
let currNum = +(string[string.length - i - 1]);
if(currNum === 1) {
decimal += bits;
}
bits *= 2;
}
console.log(decimal);
}
Another implementation just for functional JS practicing could be
var bin2int = s => Array.prototype.reduce.call(s, (p,c) => p*2 + +c)
console.log(bin2int("101010"));
+c
coerces String
type c
to a Number
type value for proper addition.Slightly modified conventional binary conversion algorithm utilizing some more ES6 syntax and auto-features:
Convert binary sequence string to Array (assuming it wasnt already passed as array)
Reverse sequence to force 0 index to start at right-most binary digit as binary is calculated right-left
'reduce' Array function traverses array, performing summation of (2^index) per binary digit [only if binary digit === 1] (0 digit always yields 0)
NOTE: Binary conversion formula:
{where d=binary digit, i=array index, n=array length-1 (starting from right)}
n
∑ (d * 2^i)
i=0
let decimal = Array.from(binaryString).reverse().reduce((total, val, index)=>val==="1"?total + 2**index:total, 0);
console.log(`Converted BINARY sequence (${binaryString}) to DECIMAL (${decimal}).`);