-2

I have created a function to convert ascii to decimal:

function asciiToDecimal(text) {
    var decimal = "";

    for (var i=0; i < text.length; i++) {
        decimal += text[i].charCodeAt(0).toString(10) + " ";
    }
    return decimal;
}

and now I want to convert binary to decimal directly. I have tried to convert to ascii and then decimal but that is not always possible. I have seen a couple of other SO Q&A that present a function, but the answer is usually not the the desired output (see below).

Input:

01101101 01111001 00100000 01101110 01100001 01101101 01100101 00100000 01101001 01110011 00100000 01101010 01101001 01101101 00111111

Desired Output:

109 121 32 110 97 109 101 32 105 115 32 106 105 109 63

How can this be achieved?

cdoublev
  • 709
  • 6
  • 18
lkdjf0293
  • 55
  • 6

1 Answers1

4

I think you're looking for the parseInt with base2 option.

parseInt(string, radix);

document.write(parseInt('01101101', 2))

And with this, you'd take your input string, split it on spaces, and parse the binary numbers individually.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

Frederik Spang
  • 3,379
  • 1
  • 25
  • 43