Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to round a number to the nearest multiple of 64

Tags:

java

I am trying to make a program that creates a square on top of a tile in a tile map. The tiles are 64 by 64. I was thinking that I need to get the coordinates of the mouse, 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 make all of the tiles buttons? Thanks!

like image 491
Fusive Avatar asked Jan 09 '23 04:01

Fusive


1 Answers

You can do this as follows:

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

It works as follows:

  1. You first add 32 (0x20) to the number so that it is rounded up/down. This means everything below 32 will result in a value less than 64 and everything larger than 32 to a value larger than 64.
  2. You mask out the last six bits.

In general bitwise operations are faster than division and multiplication. And since you ask for a power of two, it's a nice performance hack you can use.

But if you are interested in tile coordinate, you don't have to multiply it again by 64 I guess. In that case you can use:

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

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

like image 200
Willem Van Onsem Avatar answered Jan 18 '23 17:01

Willem Van Onsem