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!
source to share
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 lower32
will result in a value less than64
, and anything above will result in a value32
greater than64
. - 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.
source to share