160

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

Penny Liu
  • 15,447
  • 5
  • 79
  • 98

10 Answers10

304

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);

See it in action.

Jon
  • 428,835
  • 81
  • 738
  • 806
  • 1
    Is this still relevant? `parseInt(101, 2)` returns `5`. – srph Mar 17 '15 at 10:28
  • 20
    @srph: That's not surprising, 101 in base 2 is 5 in base 10. – Jon Mar 17 '15 at 10:41
  • 4
    Ah, I see. I must have misunderstood what the `parseInt`. I thought it would convert the string from base 10 -> whatever (thinking like `parseInt('5612', 2)` would return its binary form ;). – srph Mar 17 '15 at 13:54
  • Is it possible to make this solution work for large strings like "101110110001101000111100001110001000101000101011001100000011101"? Currently, the result is 6741077324010461000 instead of 6741077324010461213 (found with this function: https://github.com/Schmavery/facebook-chat-api/blob/22b843def642eb4ab674db33a2628c8e16ce9dcf/utils.js#L103). – baptx Dec 05 '20 at 20:03
  • @baptx almost a decade ago(!) I [answered](https://stackoverflow.com/a/5302533/50079) a different question with code that does this in PHP, I guess you can adapt that code to JS if something more convenient is not available -- function `base_convert_arbitrary`. I tested it with your example, works as expected. – Jon Dec 07 '20 at 11:59
  • @Jon thanks, so we cannot do it with just a built-in function like parseInt because it is limited to 16 digits? I thought there would be an easier solution than the one from my link. – baptx Dec 07 '20 at 22:04
  • 1
    @baptx any method at all that returns a `Number` will fail for such high values (see [this question](https://stackoverflow.com/q/307179/50079) and accepted answer). Checking the state of the art today, you should use [`BigInt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) (which is widely supported) instead. You can directly adapt [this answer here](https://stackoverflow.com/a/21722688/50079) by changing the implementation to explicitly use `BigInt` and the exponentiation operator `**` instead of `Math.pow`, and it will work. – Jon Dec 08 '20 at 13:18
  • @Jon good to know if there is no parseLong or parseBigInt function. It could be useful if you add this to your answer because sometimes StackOverflow comments are deleted without any reason. Here is what the support told me some times ago: `Comments are meant to be temporary and can be deleted at any time and for any reason, or even for no reason at all. You should not expect information in comments to stick around indefinitely.`. I tried to convert x and i with `BigInt` and use `i ** 2n` instead of `Math.pow(2, i)` but I did not get it working. – baptx Dec 11 '20 at 15:09
  • 1
    @baptx I made a fiddle [here](https://jsfiddle.net/rkvc28o1/). I don't think that this let's say "extension" merits being included in the answer though. – Jon Dec 11 '20 at 15:54
31

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
GOTO 0
  • 42,323
  • 22
  • 125
  • 158
28
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
Community
  • 1
  • 1
Md Shahriar
  • 2,072
  • 22
  • 11
15

Use the radix parameter of parseInt:

var binary = "1101000";
var digit = parseInt(binary, 2);
console.log(digit);
phihag
  • 278,196
  • 72
  • 453
  • 469
14

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);
  }
Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
3

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)

Community
  • 1
  • 1
Muhammad Musavi
  • 2,512
  • 2
  • 22
  • 35
3

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.

designcise
  • 4,204
  • 1
  • 17
  • 13
1
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);
}
madreflection
  • 4,744
  • 3
  • 19
  • 29
0

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"));
where +c coerces String type c to a Number type value for proper addition.
Redu
  • 25,060
  • 6
  • 56
  • 76
0

Slightly modified conventional binary conversion algorithm utilizing some more ES6 syntax and auto-features:

  1. Convert binary sequence string to Array (assuming it wasnt already passed as array)

  2. Reverse sequence to force 0 index to start at right-most binary digit as binary is calculated right-left

  3. '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}).`);
Isaac
  • 177
  • 1
  • 6