-1

Before I start, please don't tell me not to use eval; I know the input is perfectly sanitary, so it's safe, fast, and easy.

I'm using a JavaScript engine to power a calculator I've written in Java. To do this, I simply concatonate input into a string and pass it to JavaScript. For instance, clicking the buttons 1, +, and 5 results in building the String "1+5". I got this working for hexadecimal, too, by putting 0x before the letters, so A, +, and 8 gives me "0xA+8. My problem comes from programming its binary mode. I tried passing it 0b1101+0b10 (which is how Java does binary literals), but it just throws an error. How do I handle binary literals in JavaScript?

Ky -
  • 30,724
  • 51
  • 192
  • 308
  • 2
    http://stackoverflow.com/q/2803145/34397 – SLaks Sep 30 '13 at 20:18
  • There are MANY reasons to avoid `eval` that have nothing to do with script injection or sanitizing inputs. For one thing, it's orders of magnitude slower. For another thing, `eval` uses weird scoping rules that make it very, very easy to get subtle bugs in your code. – Justin Morgan - On strike Sep 30 '13 at 20:24
  • 1
    @JustinMorgan: You are correct. But only correct for 99.9% of cases. There is always the 0.1% freak-of-nature cases that necessitates the use of bad practice; despite the risk and maintainability problems. – Phil Jan 27 '15 at 15:54
  • @Phil I feel like mine was one. Where I am given a string like "2+8*26/0.61-0xF3" and have to give the numerical result. It's much easier to just have the JS engine evaluate it than to parse it and deal with the math myself. – Ky - Jan 28 '15 at 02:14
  • The fact that you use Java to run your calculator is not important to the question. Please remove the Java tag. – NomadMaker May 01 '20 at 15:22

1 Answers1

2

Update: As of ES2015, JavaScript supports binary Number literals:

console.log(0b1101+0b10) // 15 (in decimal)

Alternatively, you can use a string, and use Number.parseInt with a base of 2:

var a = parseInt('1101', 2) // Note base 2!
var b = parseInt('0010', 2) // Note base 2!
console.log(a+b) // 15 (in decimal)

For displaying numbers in different bases, Number#toString also accepts a base:

(15).toString(2) // 1111

Note: If passing user input directly to eval(), use a regex to ensure the input only contains numbers and the operators you expect (+, -, etc).

Ben Aston
  • 53,718
  • 65
  • 205
  • 331
alex
  • 479,566
  • 201
  • 878
  • 984
  • As I said; it's not user input. That's why I didn't want anypony to talk about eval. This is input from a compiled Java program which I have pre-programmed and formatted myself, interpreted by the internal Java JavaScript engine. – Ky - Sep 30 '13 at 23:37