I'm not too sure this will be the fastest way for your particular goal, but it's an interesting alternative route, so I'll present it anyway.

Make a copy of your first string, insert an extra "0" on the front, and do bytewise XOR. You'll end up with a string of consisting of chr(0) and chr(1), the latter if both "bits" were different. If you OR with a string of "0" characters, you'll turn that into "0" and "1" respectively. Like this:

my $str = "1010101011"; my $second = "0$str"; my $xor = $str ^ $second; my $result = $xor | "0" x length $xor;
After this, $result contains 11111111101. The first and last character are rather meaningless. But you can test whether bits with position 2, 5 and 8 pass, by extracting those characters from $result using substr.

Now, moving on to the second part of your question, You can use AND. First, make a mask, consisting of "0" characters and with the same length, setting it to "1" for those positions you're interested in. AND this with $result, and if this result is the same as $mask itself, you have a match.

my $mask = "0" x length $result; substr($mask, $_, 1) = "1" foreach 2, 5, 8; print "It passes!" if ($mask & $result) eq $mask;
and it does pass.

In reply to Re: fast bit twiddling by bart
in thread fast bit twiddling by spurperl

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.