Search code examples
groovyenumsbit-manipulationflagsdayofweek

Evaluating candidate days of the week from a bitwise total number


I have a flag enum representation of weekdays, for e.g:

weekdays{

Mon: 1
Tues: 2
Wed: 4
Thurs: 8 
Fri: 16
Sat: 32
Sun: 64
}

So, all weekdays can be represented as sum of the values of Mon through Friday

1 + 2 + 8 + 4 + 16 =31

What I want to do is deconstruct this if the value I have is 31, then how do I move backwards and infer that M, T, W, TH, Fri are the candidate days from this number.


Solution

  • you can find over the values of the enum

    enum Weekdays {
        Mon(1), Tues(2), Wed(4), Thurs(8), Fri(16), Sat(32), Sun(64)
        int bit
        Weekdays(bit) { this.bit = bit }
    }
    
    def day = 31
    println Weekdays.values().findAll{it.bit&day}
    //; [Mon, Tues, Wed, Thurs, Fri]