Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: fast bit twiddling

by bart (Canon)
on May 02, 2004 at 10:07 UTC ( [id://349790]=note: print w/replies, xml ) Need Help??


in reply to fast bit twiddling

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://349790]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (5)
As of 2024-04-23 19:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found