# Rendering 16x16 tiles, confused with the math behind it.

• 03-17-2013, 03:15 AM
eric0682
Rendering 16x16 tiles, confused with the math behind it.
• 03-17-2013, 04:16 AM
jim829
Re: Rendering 16x16 tiles, confused with the math behind it.
Code:

```public final int MAP_SIZE = 64; public final int MAP_SIZE_MASK = MAP_SIZE - 1; ... int tileIndex = ((xx >> 4) & MAP_SIZE_MASK) + ((yy >> 4) & MAP_SIZE_MASK) * MAP_SIZE; pixels[x + y * width] = tiles[tileIndex];```
Ok, this is basically using bit shifting and masking to create an index.

For every bit you shift right, you are dividing by 2.
For every bit you shift left, you are multiplying by 2.

the & is a bitwise AND operation and the | (veritical bar) is a bitwise OR. In this case the former is to zero out unwanted Higher Order Bits.

so the tileIndex = xx/16 + (yy/16) * MAP_SIZE

Using bit manipulation sometimes makes things clearer. Here, the code author used mixed methods.

I recommend checking the web for binary or bit operations for a more in depth understanding of the subject.

Regards,
Jim
• 03-17-2013, 05:00 AM
DarrylBurke
Re: Rendering 16x16 tiles, confused with the math behind it.
We don't like it when a member removes a post after there are any replies. If you do this again, you may face a ban.

Here's the removed content.

db

Quote:

Originally Posted by eric0682
Code:

```import java.util.Random;  public class Screen {  private int width, height;  public int[] pixels;  public final int MAP_SIZE = 64;  public final int MAP_SIZE_MASK = MAP_SIZE - 1;  public int[] tiles = new int[MAP_SIZE * MAP_SIZE];  private Random random = new Random();  public Screen(int width, int height) {  this.width = width;  this.height = height;  pixels = new int[width * height];  for(int i = 0; i < MAP_SIZE * MAP_SIZE; i++) {  tiles[i] = random.nextInt(0xFFFFFF);  }  }  public void clear() {  for(int i = 0; i < pixels.length; i++) {  pixels[i] = 0;  }  }  public void render(int xOffset, int yOffset) {  for(int y = 0; y < height; y++) {  int yy = y + yOffset;  //if(yy < 0 || yy >= height) break;  for(int x = 0; x < width; x++) {  int xx = x + xOffset;  //System.out.println(xx + " " + x);  //if(xx < 0 || xx >= width) break;  int tileIndex = ((xx >> 4) & MAP_SIZE_MASK) + ((yy >> 4) & MAP_SIZE_MASK) * MAP_SIZE;  pixels[x + y * width] = tiles[tileIndex];  }  }  }  }```
So in the main class, the render is called every iteration and increments one each time making it shift to the right. I don't understand the math behind tileIndex, can someone explain it to me? you can also write it like (x / 16) + (y / 16) * MAP_SIZE, which i don't understand either. which just makes a screen full of tiles randomly coloured, i don't get how it knows to group it up. PLEASE EXPLAIN

p.s i understand the >> and << bitshifts but don't understand what the & is doing