in reply to Re: help with algorithm
in thread help with algorithm

Ok, maybe I'm a little dense: if I understand you correctly, I should be able to determine "monday" from the 1 in the first position of the binary number "1010". However, how does this work for other values, like say, Tuesday, which would show up as 4, which is 100 in binary??

Replies are listed 'Best First'.
Re: Re: Re: help with algorithm
by sauoq (Abbot) on Nov 17, 2002 at 01:24 UTC

    Maybe this will make things clearer...

    my $Sun = 2**0; # That's 1 or 00000001 in binary. my $Mon = 2**1; # That's 2 or 00000010 in binary. my $Tue = 2**2; # That's 4 or 00000100 in binary. my $Wed = 2**3; # That's 8 or 00001000 in binary. my $Thu = 2**4; # That's 16 or 00010000 in binary. my $Fri = 2**5; # That's 32 or 00100000 in binary. my $Sat = 2**6; # That's 64 or 01000000 in binary. my $mask = 19; # For example. 00010011 in binary. print "Sunday\n" if ($mask & $Sun); # True print "Monday\n" if ($mask & $Mon); # True print "Tuesday\n" if ($mask & $Tue); print "Wednesay\n" if ($mask & $Wed); print "Thursday\n" if ($mask & $Thu); # True print "Friday\n" if ($mask & $Fri); print "Saturday\n" if ($mask & $Sat);
    -sauoq
    "My two cents aren't worth a dime.";
    
Re: Re: Re: help with algorithm
by larsen (Parson) on Nov 17, 2002 at 02:03 UTC
    The first example is 1010, that is (I'm considering the binary digits from right to left):

    0 * 20 + 1 * 21 + 0 * 22 + 1 * 23

    Your second example is 100. As usual, from right to left...

    0 * 20 + 0 * 21 + 1 * 22

    Got the pattern? Now I'm going to check what powers of 2 are on (i.e. multiplied by 1). In the first example they are 21 (Monday) and 23 (Wednesday). In the second example only 22, Tuesday.

    I hope this will clarify my node.