**edit** An expanded version of this post is

available at my site here.

**/edit**The bitwise technique basically does the same as a huge if/else statement, but saves on typing.

Much easier to first think of it first for a map with just two types of terrain - let's say rock and open air.

A simple map might look like this, with the filled tiles being where there's rock:

The key to the bitwise method is to assign a value to each tile depending on its neighbours. For this example let's use the following values:

We visit each tile that is meant to be filled with rock, and examine its immediate neighbours to come up with a number for that tile. If the tile directly above this one is also filled then the number is 1. If the tile directly above AND the tile directly below is filled, then the number is 1 + 4 = 5.

Here's that tile map filled out with the correct numbers.

The clever bit is we can now directly convert those numbers into graphical tiles, so skipping having to write a huge if/else statement. Here is a tileset, laid out in the order matching the valuing system we picked:

See how each tile graphic matches what would be expected of its corresponding number?

Now our game can just look at the number calculated for each filled tile, and pick out the correct tile to place there:

It would be the same principle even if you want to consider diagonal neighbours, or more varied types of terrain. You'll just end up with a larger range of numbers.

The reason it's referred to as bitwise is because the values we're assigning to neighbouring tiles follows the same 2^n pattern as binary numbers.