BitMask operation in java

Anand picture Anand · Mar 1, 2010 · Viewed 17.1k times · Source

Consider the scenario I have values assigned like these

Amazon -1

Walmart -2

Target -4

Costco -8

Bjs -16

In DB, data is stored by masking these values based on their availability for each product. eg.,

Mask product description

1 laptop Available in Amazon

17 iPhone Available in Amazon and BJ

24 Mattress Available in Costco and BJ's

Like these all the products are masked and stored in the DB.

How do I retrieve all the Retailers based on the Masked value., eg., For Mattress the masked value is 24. Then how would I find or list Costco & BJ's programmatically. Any algorithm/logic would be highly appreciated.

Answer

David Kanarek picture David Kanarek · Mar 1, 2010
int mattress = 24;
int mask = 1;
for(int i = 0; i < num_stores; ++i) {
    if(mask & mattress != 0) {
        System.out.println("Store "+i+" has mattresses!");
    }
    mask = mask << 1;
}

The if statement lines up the the bits, if the mattress value has the same bit as the mask set, then the store whose mask that is sells mattresses. An AND of the mattress value and mask value will only be non-zero when the store sells mattresses. For each iteration we move the mask bit one position to the left.

Note that the mask values should be positive, not negative, if need be you can multiply by negative one.