Fractal via bit twiddling

The Sierpinski triangle has come up several times on this blog. Here’s yet another way to produce a Sierpinski triangle, this time by taking the bitwise-and of two integers. The ith bit of x&y is 1 if and only if the ith bit of x and the ith bit of y are both 1.

The following C program prints an asterisk when the bitwise-and of i and j is zero.

    #include <stdio.h>

    int main() {
        int N = 32;
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++)
                printf("%c", (i&j) ? ' ' : '*');
            printf("\n");
        }
    }

Here’s a screenshot of the output.

screen shot that looks like Sierpinski triangle

More posts on Sierpinski triangle

2 thoughts on “Fractal via bit twiddling

  1. Thanks John. That’s an interesting pattern.
    Below is a c# implementation:

     static void Main(string[] args)
            {
                int N = 32;
                for (int i = 0; i < N; i++)
                {
                    for (int j = 0; j < N; j++)
                    {
                        Console.Write((i&j) == 0 ? '*' : ' ');
                    }
                    Console.WriteLine();
                }
                Console.ReadLine();
            }
    

Comments are closed.