Search code examples
javamathintdivisionoperation

Java - How to check if a division is an integer or a float?


Couldnt think of a better title. Well the problem is: I have the "int i", it can be any value. my goal is to transform the "int i" to the closest number divisible by 16.

For example, I got i = 33. Then i will be turned to 32 (16x2).But if I get i = 50, then it will be turned to 48 (16x3).

I tried many things for example:

for (int x = i; x < 999; x++){
if ( (i - x)/16 *is an integer*){
i = i - x;
}

But I dont know how to check if its an integer. So maybe my previous code work, but I just need to find a way to check if its an integer or a float. So.. any help is appreciated.


Solution

  • Since all ints which are divisible by 16 will have their last 4 bits all set to 0. You can accomplish what you want without a loop or even an if statement:

    i &= 0xfffffff0; // Sets i to the greatest multiple of 16 less than i, or 0 for i < 16
    

    For example:

    int i = 50;
    i &= 0xfffffff0; // i == 48
    
    i = 39;
    i &= 0xfffffff0; // i == 32
    
    i = 16;
    i &= 0xfffffff0; // i == 16