Evaluating candidate days of the week from a bitwise total number

808 views Asked by At

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.

1

There are 1 answers

0
cfrick On BEST ANSWER

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]