2
votes

I am trying to read the "day" value from native calendar of blackberry,the value is returned as a integer ,which is mapped to a value for each day of the week.The values are like :

  • Monday:32768
  • tue: 16384
  • wed :8192
  • thur :4096
  • fri :2048
  • sat :1024
  • sun :65536

I am able to see if the value is mon/tue/wed/thu/fri/sat/sun if the event is occuring for a single day using

if (rule.MONDAY == rule.getInt(rule.DAY_IN_WEEK)) {
    System.out.println("occurs monday");
}
rule.getInt(rule.DAY_IN_WEEK)

value is also same as monday value.

Now the issue is, if the events is occuring on two/three or more number of days then

rule.getInt(rule.DAY_IN_WEEK)

returns me a sum of all days selected.

EXAMPLE: if the days are :wed,sat then i get the result as 9216 ,sum of wed+sat ,from this i am not getting to know which are the days the event occurs.

How can i do a permutation/combination of these numbers and get the exact result for 'n' number of days selected.

3
you know about bitmasks ? en.wikipedia.org/wiki/Mask_(computing)leonbloy
@leonbloy no i am not aware of bit masks,how to do this? how can i achieve what i needharqs
@harqs: already answered (Thomas and ixos)leonbloy

3 Answers

4
votes

I assume the days are just bit flags in a number so you might change your check:

if ( (rule.getInt(rule.DAY_IN_WEEK) & rule.MONDAY) != 0 ) {
   System.out.println("occurs monday");
}
3
votes

Use binary and operator like this:

int day = rule.getInt(rule.DAY_IN_WEEK)
if(day & rule.MONDAY != 0) {
 System.out.println("occurs monday");
}
if(day & rule.WEDNESDAY != 0) {
 System.out.println("occurs wednesday");
} /* and so on */

Notice that:

0000 0100 0000 0000 = 1024

0000 1000 0000 0000 = 2048

. . . check also bit mask

2
votes

To know which days of the week the event occurs, you need to do something like this:

boolean occursOnMonday = (rule.getInt(rule.DAY_IN_WEEK) & rule.MONDAY) != 0;

where & is the bitwise AND operator. Why is this so?

Wednesday is 8192, which in binary it is 10000000000000 (2 times 13)

Saturday is 1024, which in binary it is 00010000000000 (2 times 9)

So an event that happens on Wed and Sat is 9216, which is 10010000000000.

Then using bit operations you are able to know what bits are in 1 and what bits are in 0, and with that you know what days the event happens.