0

I have come across strange operators such as &, |, ^ etc. How exactly do these operators work?

>>> 10 | 7
15
>>> 10 ^ 7
13
>>> 10 & 7
2
>>> 

The pattern does seem quite odd, and most of the sources out there do not give answers that are easy to comprehend.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
user1823
  • 1,111
  • 6
  • 19
  • They operate on the bits - the 0s and 1s. It won't make much sense if you're looking at the numbers' decimal representations. – TigerhawkT3 May 08 '15 at 05:29
  • @TigerhawkT3 yes, I am aware, which is why I answered it further down. However, I, like many others, was confused by them when I first started coding, and I hope this will serve as something like a reference. – user1823 May 08 '15 at 05:30
  • I'm voting to close this question as off-topic because SO is not a blog. – TigerhawkT3 May 08 '15 at 05:31
  • @TigerhawkT3: Self-answered questions are completely fine on SO. However, I find it hard to believe this one doesn't have a duplicate somewhere. – Cerbrus May 08 '15 at 05:32
  • 1
    @user1823: either tag this with JavaScript, or with Python. Not with both. – Cerbrus May 08 '15 at 05:35
  • "How exactly do these operators work?" I'm excited and can't wait to see some circuit diagrams of how to implement AND, OR and eXclusiveOR gates for a 32-bit binary number! – Paul S. May 08 '15 at 05:45
  • @user1823: If you're going to post something like this on SO, it's generally a good idea to stick around a bit to respond to comments / questions. – Cerbrus May 08 '15 at 05:50

2 Answers2

0

BITWISE AND

Each item in row 1 is multiplied by the corresponding value in row 2:

a = 5     # In binary: 0101
b = 3     # In binary: 0011
c = a & b # In binary: 0001

print c   # In decimal: 1

BITWISE OR

If any item in either row is 1, the corresponding result is 1:

a = 5     # In binary: 0101
b = 3     # In binary: 0011
c = a | b # In binary: 0111

print c   # In decimal: 7

BITWISE XOR

If the items in each column are different from each other, the result is 1:

a = 5     # In binary: 0101
b = 3     # In binary: 0011
c = a ^ b # In binary: 0110

print c   # In decimal: 6
user1823
  • 1,111
  • 6
  • 19
-2

This might be helpful to you

Bitwise operators guide in MDN

You can use chrome javascript console to test all these operators also.

In javascript try like this

var a = 5;
var b = 6;



console.log((a & b)); //AND

console.log((a | b)); //OR

console.log((a ^ b)); //XOR

console.log((~a)); //NOT

console.log((a << b)); //Left Shift

console.log((a >> b)); //Sign propagating right shift

console.log((a >>> b)); //Zero fill right shift
Dave
  • 494
  • 6
  • 21