boolean operations with integers

David Brown picture David Brown · Nov 26, 2008 · Viewed 7.5k times · Source

This is probably pretty basic... but I don't seem to get it:

How does

(2 & 1) = 0
(3 & 1) = 1
(4 & 1) = 0

etc..

This pattern above seems to help find even numbers

or

(0 | 1) = 1
(1 | 1) = 1
(2 | 1) = 3
(3 | 1) = 4
(4 | 1) = 5
(5 | 1) = 5

I know how boolean algebra works between bits. But I don't understand how Boolean algebra works with integers (in C# at the least).

thanks in advance.

Answer

SoapBox picture SoapBox · Nov 26, 2008

It works the same way in C# as it does in binary.

2 | 1 = 3 and 4 | 1 = 5.

To understand this, you need to think about the binary representation of 1,2,3,4,and 5:

010 | 001 = 011 and 100 | 001 = 101.

Similarly:

010 & 001 = 000 and 011 & 001 = 001