javascript - How do the bitwise operations work? -


this question has answer here:

i have come across strange operators such &, |, ^ etc. how these operators work?

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

the pattern seem quite odd, , of sources out there not give answers easy comprehend.

bitwise and

each item in row 1 multiplied corresponding value in row 2:

a = 5     # in binary: 0101 b = 3     # in binary: 0011 c = & b # in binary: 0001  print c   # in decimal: 1 

bitwise or

if any item in either row 1, corresponding result 1:

a = 5     # in binary: 0101 b = 3     # in binary: 0011 c = | b # in binary: 0111  print c   # in decimal: 7 

bitwise xor

if items in each column different each other, result 1:

a = 5     # in binary: 0101 b = 3     # in binary: 0011 c = ^ b # in binary: 0110  print c   # in decimal: 6 

Comments