Search code examples
javamathbitwise-operators

Calculating number bonds to value in Java


As part of my application, the database stores "badges" in a user's record in the database. I use the bitwise operator as (as far as I know) no two additions of them can have the same solution. Here are the values:

enum Badge {
        SUPPORTER(1),
        ALPHA(1 << 1),
        BETA_OWNER(1 << 2),
        BOOSTER(1 << 3),
        ONE_MONTH(1 << 4),
        THREE_MONTH(1 << 5),
        SIX_MONTH(1 << 6),
        ONE_YEAR(1 << 7),
        TWO_YEAR(1 << 8),
        ;

        public int value;
        
        public int resolve() {
            return value;
        }

        Badge(int i) {
            value = i;
        }
    }

The method of storing them is as simple as adding up the values of each badge corresponding to the user. However, decoding this value is more tricky.

How would I go about decoding the value from the database into a list of badges that I can manipulate?


Solution

  • Use an EnumSet.The EnumSet can hold each item only once (it's a set). Have a look here for storing values in a database. There are solutions for decoding manually, or you can use Apache Commons for that.