Reputation: 7488
I need to do bitwise OR of two binary strings.
For example, if the binary strings are '110001' and '101101', then I need the result as '111101'.
I tried this, but it gave me strange results.
console.log(110001 | 101101);
Upvotes: 0
Views: 130
Reputation: 74244
You can't write binary numbers as literals in JavaScript. The only numeric literals allowed are:
1337
(One thousand and thirty-seven).02471
(One thousand and thirty-seven in base 8).0x539
(One thousand and thirty-seven in base 16).To write binary numbers you need to use parseInt
with base 2. To convert a number to binary representation you use toString
with base 2. Hence you would write it as:
var a = parseInt("110001", 2);
var b = parseInt("101101", 2);
var c = a | b;
console.log(c.toString(2));
Simple.
Upvotes: 3
Reputation: 1917
You need to explicitly cast the binary representation to it's int equivalent. (otherwise it's interpreted as 110001 (base 10)):
console.log((parseInt('110001',2) | parseInt('101101',2)).toString(2));
The output is then cast back to it's base 2 representation (string)
Upvotes: 2