unixhome has asked for the wisdom of the Perl Monks concerning the following question:

Hello helpful Monks: This time I have a question about how to display a particular byte of binary data, bit-by-bit in it's binary representation as (01001010) for example. I have already written something like:
printf ("\tByte 0 looks like: 0x%08b\n\n", ord $uh[0]);
But it would be very helpful to me to be able display the data bit-by-bit. Thanks in advance, Ronald Vazquez

Replies are listed 'Best First'.
Re: Help displaying binary data bit-by-bit in binary notation
by Zaxo (Archbishop) on Jun 15, 2006 at 02:52 UTC

    See vec, if you're asking what I think you are. pack, unpack, and sprintf are also useful for dealing with bit vectors and "binary" strings.

    If you're talking about numeric data, the bitwise operators from perlop will do the job.

    After Compline,
    Zaxo

Re: Help displaying binary data bit-by-bit in binary notation
by bobf (Monsignor) on Jun 15, 2006 at 02:52 UTC

    Have you tried the pack function (and its counterpart unpack)? If I understood your question correctly, that might be what you're looking for. Here's a quick example:

    use strict; use warnings; my $string = 'a'; print 'unpack b = [', unpack( "b*", $string ), "]\n";
    This prints unpack b = [10000110].

    If you want something else, please be more specific.

    HTH

      HTH: Yes, your unpack b is close to what I need if we could only get it to display the binary number one bit at-a-time. Like:
      unpack b = 1 0 0 0 1 1 0
      Thanks, RV

        Since unpack returns a string, simply add a bit (pun intended) of split and you're done:

        my $bin_str = unpack( "b*", $string ); print join( "\n", split( //, $bin_str ) );

        Updated output:

        unpack b = [10000110] 1 0 0 0 0 1 1 0