0

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); 
5
  • 5
    Did you try console.log((parseInt("110001", 2) | parseInt("101101", 2)).toString(2))? Commented Jul 1, 2014 at 2:58
  • The logical OR Of one hundred and ten thousand and one, with one hundred and one thousand, one hundred and one ... what's strange, exactly? Commented Jul 1, 2014 at 3:00
  • @Pointy It's binary digit. Why do you feel strange? Commented Jul 1, 2014 at 3:04
  • @Tyler.z.yang JavaScript doesn't think those are binary digits. Those are plain base-10 numbers :) Commented Jul 1, 2014 at 3:05
  • 1
    @Pointy Yeah, what I mean is Foreever want to explain this into binary digits. Commented Jul 1, 2014 at 3:06

2 Answers 2

3

You can't write binary numbers as literals in JavaScript. The only numeric literals allowed are:

  1. Decimal: 1337 (One thousand and thirty-seven).
  2. Octal: 02471 (One thousand and thirty-seven in base 8).
  3. Hexadecimal: 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.

Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.