in reply to Printing, analyzing binary

N.B. sprintf("%08b", ord $byte) will only work with 5.6.0 and later. For 5.005_xx, use unpack.

You can also use the new vector modifier 'v' to avoid the ord (or to output multiple bytes worth at once):

$ perl5.6.2 -we'$x = "\x01"; printf "%0v8b", $x' 00000001 $ perl5.6.2 -we'$x = "\x01\x02"; printf "%0v8b", $x' 00000001.00000010
If you want just an uninterrupted stream of digits for the latter, remove the .'s afterward:
$ perl5.6.2 -we'$x = "\x01\x02"; $binary = sprintf "%0v8b", $x; > $binary =~ tr/.//d; print $binary' 0000000100000010

Replies are listed 'Best First'.
Re: Re: Printing, analyzing binary
by perlfan (Parson) on Apr 26, 2004 at 18:24 UTC
    Thanks, guys - here is what I ended up doing:
    my $buffer; open INF, $srcfile or die "\nCan't open $srcfile for reading: $!\n"; binmode INF; while (read (INF, $buffer, 1)) { # to string my $bits = unpack("b*", $buffer); # count total length, though = # bits my $tot = length($bits); # count 1s my $num1s = 0; while ($bits =~ /1/g) { $num1s++ }; # count 0s my $num0s = 0; while ($bits =~ /0/g) { $num0s++ }; # print info print "$bits\n"; print "$num1s 1's; $num0s 0's; $tot total length\n"; }
    Something I have encountered during my research is the "vec" function (built in) and the Bit::Vector module. Am I correct to assume that both of these provide some level of functionality meant to easily manage/manipulate a series of bits (or boolean values) that are contained inside of an array? TIA