Skip to content
Adrien Hubert

Hilbert curve, one order at a time.

A Hilbert curve is one continuous line that visits every cell of a square grid exactly once, never crossing itself. Order one is a simple staple. Every next order swaps each cell for a rotated copy of the previous order and joins them with three short bridges. After a few doublings the line is dense enough to look like a filled square, and two indices that sit near each other on the line almost always sit near each other in the plane.

Order 4
Grid 16 × 16
Cells 256
Index at cursor

Hover the square to read the 1D index at that cell

4
100%

Four rotated copies

An order-n curve fits in a 2^n by 2^n grid. To build order n from order n minus one, split the square into four quadrants and drop a copy of the smaller curve into each. The two bottom quadrants get rotated, the bottom-left one clockwise and the bottom-right one counterclockwise, so that the exits of each quadrant line up with the entries of the next. Three straight segments link them in the order bottom-left, top-left, top-right, bottom-right. The same rule applies at every scale, which is why the curve looks self-similar all the way down.

Why anyone cares

A Hilbert curve turns a 2D coordinate into a single integer and vice versa, and it does so while keeping nearby cells nearby in both directions. That property is what makes it useful outside of posters. Image-processing kernels traverse pixels along a Hilbert order so that a cache line covers a compact block. Spatial databases index points by their Hilbert index so that a range query on the index returns a compact patch of space. The IP-space map on xkcd 195 lays out the entire IPv4 address space along an order-12 curve so that neighbouring address blocks are drawn as neighbouring squares.

Sources

  • Hilbert, D. (1891). Ueber die stetige Abbildung einer Linie auf ein Flächenstück. Mathematische Annalen 38, 459–460. The original two-page note, published a year after Peano's first space-filling curve.
  • Sagan, H. (1994). Space-Filling Curves. Springer. A modern reference on the family, including Peano, Hilbert, Moore and Sierpinski variants.
  • Munroe, R. (2006). xkcd 195: Map of the Internet. xkcd.com/195. The IPv4 layout that most people meet the Hilbert curve through.
  • Bit-manipulation routine for the 1D-to-2D conversion adapted from the pseudocode in the Wikipedia article on the Hilbert curve.