Article 4VPG8 Fractal via bit twiddling

Fractal via bit twiddling

by
John
from John D. Cook on (#4VPG8)

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.

sierpinski_bits.png

More posts on Sierpinski trianglemYRtt3BC3A4
External Content
Source RSS or Atom Feed
Feed Location http://feeds.feedburner.com/TheEndeavour?format=xml
Feed Title John D. Cook
Feed Link https://www.johndcook.com/blog
Reply 0 comments