
The beauty of bitwise AND - coinomega
https://medium.com/biffures/part-2-the-beauty-of-bitwise-and-or-cdf1d8d87891#.vi8997ogc
======
pdpi
"Bitwise" is really shorthand for "this is an operation that acts on the
representation of a number in base-2, rather than on the number itself", so
it's no surprise that it doesn't translate well to base 10. The reason why
that formula is so gnarly is that it does three things in one go:

\- convert x and y from decimal to binary

\- calculate x AND y at each digit (by using the property that x AND y is
isomorphic to multiplication mod 2)

\- convert back to decimal.

Instead of trying to understand bitwise AND in this way, we could try building
the equivalent operation in base 10, and see where that leads us. One simple
way of achieving this is by simply saying that x AND Y is digit-wise MIN, and
x OR y is digit-wise MAX.

Note how, under that interpretation, this works in both binary and decimal (or
hex, or octal, or whatever other base you want:

101 AND 110 = 100

101 OR 110 = 111

Or using digits not available in binary:

124 AND 310 = 110

124 OR 310 = 324

Again, this works independently of whether you're using octal, decimal, hex,
or something else >= 5.

~~~
wyldfire
This is pretty interesting, but I'm missing something. Intuitively, your
digit-wise MIN description of 'AND' makes sense to me. But your examples don't
work when using two's complement encoded versions of them. 124 & 310 == 52
right? Help me connect the dots.

~~~
pdpi
See it this way: Numbers are distinct from their representations. 0x10, 0o20,
16 and 0b10000 are four different representations of the same number. The &
operator doesn't operate on _numbers_, it operates on their binary
representation — in many ways, it's almost like string manipulation.

What I suggested was that that way of operating on the representation of the
number would work on any base in a way that is consistent (but, importantly,
doesn't yield the same numerical result!) with the binary version.

------
bugmenot3
I knew I'd seen this pattern before! The XOR texture [1] is very similar.
Apparently it was overused in early 2D games to test texture mappers (or for
"fancy floor tiles", lol)

Actually, looking at the XOR, AND, OR textures side by side, it's easy to gain
more intuition for them.

I definitely recommend reading some of the articles at [2], they're pretty
entertaining and straight-forward.

[1]
[http://lodev.org/cgtutor/xortexture.html](http://lodev.org/cgtutor/xortexture.html)

[2] [http://lodev.org/cgtutor/](http://lodev.org/cgtutor/)

~~~
userbinator
Very common in the demoscene too, along with the related Sierpinski triangle
texture:

[https://en.wikipedia.org/wiki/File:Multigrade_operator_AND.s...](https://en.wikipedia.org/wiki/File:Multigrade_operator_AND.svg)

------
atemerev
I remember the pattern, I do!

Back in the year 1992, when I was 9 years old, I participated in the first
tour of Russian programming olympiad. The first challenge was this one:

"On the infinite coordinate grid (positive integers only), start with the
number 0 in the cell with coordinates (0,0). Then, in each cell in the
neighbourhood, write the largest integer that hadn't yet appeared in the same
row or column. Repeat indefinitely.

Find the formula for obtaining the value inside any arbitrary cell in the
grid."

I have filled a 16x16 grid using this definition manually (of course, the
programming olympiad had nothing to do with computers — similar to whiteboard
coding during the job interviews these days), and obtained similar pattern. As
this task was by far the most interesting in the problem set, I have spent the
entire allotted time trying to figure out the formula, without success — so I
got 0 points and went out of the competition.

And now, 24 years later, I see the solution (not the AND; the pattern looks
slightly different, perhaps XOR?) But I should have tried bitwise operations
back then. Damn it!

~~~
Sniffnoy
Do you mean the _smallest_ whole number that hasn't appeared yet? But yup,
that's a well-known recursion for XOR, important in combinatorial game theory,
in which context it's often known as the Nim sum.

(Note by the way, that the initial condition about (0,0) can be omitted -- at
that point, there are no numbers in that row or column, so the smallest one
available is 0!)

Topics you might want to look up:
[https://en.wikipedia.org/wiki/Combinatorial_game_theory](https://en.wikipedia.org/wiki/Combinatorial_game_theory)
[https://en.wikipedia.org/wiki/Nim](https://en.wikipedia.org/wiki/Nim)
[https://en.wikipedia.org/wiki/Sprague%E2%80%93Grundy_theorem](https://en.wikipedia.org/wiki/Sprague%E2%80%93Grundy_theorem)
[https://en.wikipedia.org/wiki/Mex_(mathematics)](https://en.wikipedia.org/wiki/Mex_\(mathematics\))
[https://en.wikipedia.org/wiki/Nimber](https://en.wikipedia.org/wiki/Nimber)

~~~
atemerev
Yes, the smallest, of course.

------
lokedhs
Can someone explain this sentence to me?

(In the quote below, he names the AND function "f", which in itself is a bit
strange. What's wrong with "and" or ∧?)

    
    
      f(a, b) produces at most a or b, whichever is greater:
        f(a, b) ≤ max(a, b)
    

As far as I can tell, the result can never be greater than the smaller of a
and b. I can't come up with a counterexample. Is there one?

~~~
bnegreve
> _In the quote below, he names the AND function "f", which in itself is a bit
> strange. What's wrong with "and" or ∧?_

'∧' usually denotes the logical AND operator, which does not operate on
integer values, (i.e. writing 22 ∧ 78 = 6 is weird). So it's not a bad idea to
give this function a different name.

He could have made that explicit though.

------
inductiveload
Every binary operation has an associated texture. If you plot integer
operations as colours or rings[1], you get other interesting results that
provide insights into how the operands affect the result.

[1]
[https://commons.wikimedia.org/wiki/Category:Binary_ring_diag...](https://commons.wikimedia.org/wiki/Category:Binary_ring_diagrams)

------
dingo_bat
I always thought ^ is the XOR operator, not AND.

~~~
posterboy
In boolean algebra, * (a dot, actually) and + are used for And and Or and the
usual rules about association and commutation are used (PEMDAS, kinda,
ommiting the * on occasion). Sometimes, what I might call, up arrow and down
arrow are used, looking similar to ^ and v, in relation to set arithmetic
symbols for the union and intersection oprators.

~~~
svalorzen
Another way to easily remember the arrows is to associate them with words: ^
with the A of and, and v with the V for vel (Latin for or). I always did this
in logic class since I would always get confused otherwise.

~~~
TeMPOraL
I remembered these and union/intersection sign by imagining balls falling on
the symbols from above - in case of V (OR) they would end up inside the
symbol, which suggest summing/union, and in case of ^ (AND) they would get
split and collect on opposite sides.

------
joveian
I like the 1024x1024 picture; it looks a bit like a bird to me, or maybe a
stingray.

One interesting application of bitwise AND is in cryptography, particularly
LRX (logical rotations and xor) algorithms popularized by Keccak/SHA-3. By
using only these limited operations, masking (blinding) becomes much more
efficient that makes various side channel attacks harder [0]. Several of the
CAESAR AEAD competition candidates are LRX. NORX uses only AND, XOR, and
rotation.

[0]
[http://keccak.noekeon.org/NoteSideChannelAttacks.pdf](http://keccak.noekeon.org/NoteSideChannelAttacks.pdf)

------
snaky
The beauty of shift -
[http://yarchive.net/comp/shift_instruction.html](http://yarchive.net/comp/shift_instruction.html)

------
e19293001
I remember I asked a question 5 years ago in stack overflow[0] about the
mathematical equation equivalent of bitwise AND. Thank you for posting this I
found the answer to my 5 year old question.

[0] - [http://stackoverflow.com/questions/7199625/mathematical-
equa...](http://stackoverflow.com/questions/7199625/mathematical-equation-for-
and-bitwise-operation)

~~~
jonsen
The formula in the accepted answer on SO is equivalent to the formula in this
article. Just written differently.

------
threepipeproblm
If b is the number of bits, shouldn't the upper bound of the sigma be b-1?

~~~
coinomega
corrected

------
_RPM
The image seems to be doing b1 ^ b2 (which would be a XOR), but the result is
the result of & (AND)

~~~
coinomega
∧ is also the notation for bitwise AND

[http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4....](http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf)

~~~
_RPM
Ahh. Okay. I'm just assuming that they would do these computations using a C
like language.

------
tr352
The complexity of the formula and the "striking features" of the graph only
demonstrate that operations defined in one base (AND is nothing but
multiplication in base 2) may behave in complex and non obvious ways in other
bases.

~~~
TTPrograms
AND is vector entry-wise multiplication (hadamard product) with boolean
entries, not just multiplication in base 2. Multiplication between numbers is
not affected by base - base just defines how the number is written down.

~~~
tr352
It's multiplication in the sense that for two base-2 numbers A and B, A & B is
the same as A * B, but I get your point.

~~~
jonsen
For two _bits_ AND is multiply, not for two numbers in general, regardless of
base.

------
known
XOR swap algorithm
[https://en.wikipedia.org/wiki/XOR_swap_algorithm](https://en.wikipedia.org/wiki/XOR_swap_algorithm)

