Search code examples
javabitwise-operatorsbitwise-and

Benefit of using bitwise AND operator between integers?


I was looking at some code which is like:

public int someMethod(String path, int maxCallers) {

        int hash = path.hashCode();
        int caller = (hash & Integer.MAX_VALUE) % maxCallers;
        return caller;
    }

This method returns which caller to be called based on the path. If the maxCallers value is 4 the caller value should be between 0-3. Now here i don't understand the use of doing hash & Integer.MAX_VALUE. One reason i can think of is the programmer wants a positive number as hashcode can be negative, but i think my understanding is wrong here. Can someone please explain the use of bitwise AND operator here.


Solution

  • Your assumption is correct. It's to remove the sign of the integer in case the hash is negative. ANDing with Integer.MAX_VALUE will remove the sign bit from the integer. Note that this is different from getting the absolute value of the integer:

    int hash = -1;
    int caller = (hash & Integer.MAX_VALUE) % 4;  // returns 3
    
    int hash = -1;
    int caller = Math.abs(hash) % 4;  // returns 1