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