Just another Perl shrine | |
PerlMonks |
Re: Working with Binary Numbersby Anno (Deacon) |
on Sep 24, 2007 at 22:17 UTC ( [id://640835]=note: print w/replies, xml ) | Need Help?? |
I like blokhead's glob()-based solution. Here is one that is based on binary arithmetic (aka bit fiddling).
Essentially, filling in the dashes in a template amounts to counting upwards the bits indicated by dashes while keeping the other bits unchanged. For n dashes, this results in 2**n values. The subroutine increment_masked() below does one counting step arithmetically, given a value and a mask indicating the original position of dashes. To expand a template of zeroes, ones, and dashes, extract from the template a mask (a number with 1-bits where dashes were, 0-bits otherwise), and a starting value (a number with zeroes where dashes were, other bits unchanged from the template). Apply increment_masked() appropriately to the starting value and collect the results. This is what the sub expand() does. The final result is achieved by mapping expand() over the given templates. Anno
Update: Typos corrected
In Section
Seekers of Perl Wisdom
|
|