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?
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).