How to round a number to the nearest multiple of 64

I am trying to create a program that creates a square on top of a tile in a tile map. The tiles are 64 by 64. I thought I needed to get the mouse coordinates, round it to the nearest multiple of 64, and divide that by 64 to get the tile coordinate. Is there a better way? Should I do all the buttons on the tiles? Thank!

+3


source to share


2 answers


You can do it like this:

int number = 445226;
int roundoff = (number+0x20)&(~0x3f);

      

It works like this:

  • First, you add 32

    ( 0x20

    ) to the number to round up / down. This means that anything lower 32

    will result in a value less than 64

    , and anything above will result in a value 32

    greater than 64

    .
  • You mask the last six bits.


In general, bitwise operations are faster than division and multiplication. And since you're asking for strength of two, this is a good performance hack that you can use.

But if you're interested in the coordinate of a tile, you don't need to multiply it by again 64

. In this case, you can use:

int number = 445226;
int div64 = (number+0x20)>>0x06; //this is divided by 64, not rounded

      

About the UI, as always, the multiple answers are correct, but if you're going to draw some kind of map on it, I think coordinates are better than buttons. Especially if, later in the process, people will be able to click on the items on the map that lie between the two buttons.

+7


source


For natural numbers:

int m64 = 64 * ((n + 32) / 64);

      



Or more fantastically, because 64 has a strength of 2:

int m64 = ((n + 32) >> 6) << 6;

      

+2


source







All Articles