in reply to oct and vec

This is an example of a bit vector (a vector of "0"s or "1"s)

## Define a bit vector with positions 4 to 7 set to 1 my $bv1=''; vec($bv1,$_,1)=1 foreach (3..6); dumpbv($bv1); sub dumpbv { my $bitv = shift @_; my $pos=0; foreach (split "",unpack("b*",$bitv)){ print; $pos++; } }

With bit vectors you can do bit operations. for example, to find the overlapping ("OR") of 2 bit vectors:

sub sumbv { return $_[0] | $_[1]; }

... and the AND operation:

sub cmpbv { return $_[0] & $_[1]; }

A full working dummy example with these functions would be:

use strict; use warnings; ## Define a bit vector with positions 4 to 7 set to 1 my $bv1=''; vec($bv1,$_,1)=1 foreach (3..6); dumpbv ($bv1); print " bv1\n"; # Define a bit vector with positions 3 to 5 set to 1 my $bv2=''; vec($bv2,$_,1)=1 foreach (2..4); dumpbv ($bv2); print " bv2\n"; print "--------\n"; my $bv_sum = sumbv($bv1,$bv2); dumpbv ($bv_sum);print " OR\n"; my $bv_cmp = cmpbv($bv1,$bv2); dumpbv ($bv_cmp);print " AND\n"; sub sumbv { return $_[0] | $_[1]; } sub cmpbv { return $_[0] & $_[1]; } sub dumpbv { my $bitv = shift @_; my $pos=0; foreach (split "",unpack("b*",$bitv)){ print; $pos++; } }

Outputs:

00011110 bv1 00111000 bv2 -------- 00111110 OR 00011000 AND

Hope this helps

citromatik

Replies are listed 'Best First'.
Re^2: oct and vec
by mikejones (Scribe) on Aug 07, 2007 at 17:13 UTC
    How are any of these code examples useful and or how are you applying these in a work environment?
      The ability to manipulate bits is essential in many low level tasks and in some memory-efficient algorithms.