Programmer [aemkei] Tweeted the formula (x ^ y) % 9
alongside code for more “alien art”. But how can a formula as simple as (x ^ y) % 9
result in a complex design? The combination of Bitwise XOR (^
) and Modulo (%
) generate a repeating pattern that’s still complex enough to satisfy the eye, and it’s ok if that doesn’t sound like an explanation. Bitwise operations are useful when working with memory and shift registers, but also worth learning if you want to drive lines or matrices of LEDs or interpret combinations of multiple switches, or in this case a great way to throw an interesting test pattern up on a new flip-dot display or low-res LED matrix. Are you into it? We are, so let’s jump in.
XOR Truth Table
|
0b00 |
0b01 |
0b10 |
0b11 |
0b00 |
0b00 |
0b01 |
0b10 |
0b11 |
0b01 |
0b01 |
0b00 |
0b11 |
0b10 |
0b10 |
0b10 |
0b11 |
0b00 |
0b01 |
0b11 |
0b11 |
0b10 |
0b01 |
0b00 |
Bitwise XOR compares each binary digit of the two inputs. The XOR returns a 1 when only one of the two digits is a 1, otherwise, it returns a zero for that position. Let’s say the coordinates were 3, 2. Converted to binary we have 0b11 and 0b10. From this truth table, we can see the most-significant digits are both 1, returning a 0, while only one of the least-significant digits is a 1, so the comparison returns a 1.
Moving onto the %, which is the Modulo operator has nothing to do with percentages. This operator divides two numbers and returns the remainder if any. Take 9 % 5
. When dividing 9 by 5, 5 goes in once with a remainder of 4 so 9 % 5 = 4
. Now our original formula from the top will draw a black box for every ninth number except that the bitwise XOR throws a wrench into that count, varying how often a number divisible by 9 appears and supplying the complexity necessary for these awesome patterns.
What are the most interesting designs can you create in a simple formula?