BazB has asked for the wisdom of the Perl Monks concerning the following question:
Greetings,
In a recent project, I needed some code that applied a mask against a bitstring.
I didn't have a clue how to achieve that sort of thing at the time, so the fabulous BrowserUk supplied the following code to XOR and AND
the two strings:
my @xored = map { ord } split //, $str1 ^ $str2; my @anded = map { ord } split //, $str1 & $str2;
At the time, I was looking for fast ways of doing things, and I
remembered Bit::Vector can do this sort of thing (and a lot more
besides), so I came up with the following:
use Bit::Vector; sub gen_xor { my $len = length $_[0]; my $vec1 = Bit::Vector->new_Bin($len, $_[0]); my $vec2 = Bit::Vector->new_Bin($len, $_[1]); $vec2->Xor($vec1, $vec2); $vec2->to_Bin(); } sub gen_and { my $len = length $_[0]; my $vec1 = Bit::Vector->new_Bin($len, $_[0]); my $vec2 = Bit::Vector->new_Bin($len, $_[1]); $vec2->And($vec1, $vec2); $vec2->to_Bin(); } print gen_xor('10011', '01110'), "\n"; print gen_and('10011', '01110'), "\n";
Although the original code that inspired this post only required XOR or AND, I'd also be interested to see two bitstrings NAND'ed too.
Golf, Obfu, or truly useful code, please post below!
Cheers
BazB
Update: Corrected first code section.
If the information in this post is inaccurate, or just plain wrong, don't just downvote - please post explaining what's wrong.
That way everyone learns.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: XOR, AND or NAND'ing bitstrings.
by pg (Canon) on Jan 27, 2003 at 01:25 UTC | |
|
Re: XOR, AND or NAND'ing bitstrings.
by jryan (Vicar) on Jan 27, 2003 at 05:13 UTC | |
|
Re: XOR, AND or NAND'ing bitstrings.
by pg (Canon) on Jan 27, 2003 at 20:17 UTC |