Skip to content

XOR and AND Patterns

Compare the binary digits of a pixel's x and y and you get squares inside squares, or a Sierpinski triangle, from one operator.

How it works

x ^ y (XOR) looks at the binary digits of x and y and gives a 1 wherever they differ. Binary digits repeat at sizes 1, 2, 4, 8, 16 and so on, so the result is a pattern of squares nested inside squares. It can be as big as 511 on a 300-pixel picture, so % 256 keeps it to 0..255 and dividing by 255 turns it into the 0..1 a colour needs.

x & y (AND) gives a 1 only where both have a 1 digit. The pixels where the result is zero form the Sierpinski triangle, a fractal.

Testing the XOR value with % picks out a set of lines from it, and every number gives a different weave.

In C the operators need whole numbers, so the pixel's position is turned into an int first, and 255.0f keeps the division from being whole-number division (which would give 0). The C is for the raylib pixels starter.

XOR as a shade of grey

static RGB shade(float x, float y, float t)
{
    return grey(((int)x ^ (int)y) % 256 / 255.0f);
}
function shade(x, y, t) {
  return grey((x ^ y) % 256 / 255);
}

AND: the Sierpinski triangle

static RGB shade(float x, float y, float t)
{
    return grey(((int)x & (int)y) == 0 ? 1 : 0);
}
function shade(x, y, t) {
  return grey((x & y) === 0 ? 1 : 0);
}

A weave: XOR tested with modulo

Try other numbers instead of 9.

static RGB shade(float x, float y, float t)
{
    return grey(((int)x ^ (int)y) % 9 == 0 ? 1 : 0);
}
function shade(x, y, t) {
  return grey((x ^ y) % 9 === 0 ? 1 : 0);
}

In colour, moving

Add time to the XOR value before the palette and the colours flow through the squares.

static RGB shade(float x, float y, float t)
{
    return rainbow(((int)x ^ (int)y) % 256 / 255.0f + t * 0.1f);
}
function shade(x, y, t) {
  return rainbow((x ^ y) % 256 / 255 + t * 0.1);
}