Bits implements an array of 0's and 1's with a few binary math operations and input/output formats.
use Bits;
$m = new Bits binary => '0011_0101_0001_1000'; # underbars optional $p = new Bits hex => '61_62_6d_6e'; # ditto $n = new Bits number => 97; $q = new Bits raw => 'hello'; print $q->as_hex; # "68656c6c6f"; error if size isn't a multiple of 4 print $n->as_text; # "0110_0001"; same as "$n" print $p->as_raw; # "abmn" print $m->as_number; # 13592 ; same as 0+$m
print $m->size; # 16 $m << 3; # left shift 3 bits; wraps around $m >> 6;
$r = $n ^ $m; print $r; # "Oops: attempted Bits XOR on differing sizes" print $r->error; # same; can be tested for error conditions. $m = new Bits binary => '1111'; $n = new Bits binary => '0101'; $p = $m . $n; # concatenation = Bits->new( binary => '1111_0101') $q = $m ^ $n; # binary xor
my $z = $m->clone; # deep copy print $z->get(0); # 0'th bit of $z (indeces are like arrays: 0,1,2,...) $z->set(3,0); # set 3rd bit of $z to 0.
$x = new Bits binary => '1001'; $y = $x->permute(1,0,3,2); # "0110" $z = $x->permute(0,0,1,1,2,2,3,3); # "1100_0011"
Run ``./test_Bits.pl'' to see the tests.
This hasn't been tested on large sizes or numbers; I'm just looking for the basics for now.
The $bit->set($index,$value)
function gives an error
(by setting $b->error) if either
(a) the $index is smaller than 0 or larger than $bit->size()-1, or
(b) the $value is anything other than a 0 or 1.
Not yet implemented :
* $bits->permutate( @array ); # rearrange bits
* $bits->reverse();
* $bits->not() = ~ $bits; # bitwise "not"
* $bits->and($z) = $bits & $z; # bitwise "and"
* $bits->or($z) = $bits | $z; # bitwise "or"
* handle numbers bigger than perl's standard ints
Copyright 2005 Jim Mahoney, Marlboro College (mahoney@marlboro.edu)
This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself.