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

I'm sure this is going to be really basic, but I've gone several decades using Perl and never needed the pack or unpack functions before.

#!/usr/bin/perl use strict; use warnings; # my $pReqsca = "ABCD"; my @bytary = unpack 'C*', $pReqsca; + my $binstr = ''; + foreach my $scabyt (@bytary) { + my $intbyt = int($scabyt); + my $hexbyt = sprintf("%02X", $intbyt); + my $binbyt = unpack 'b8', $scabyt; + $binstr .= $binbyt; + print " Byte = [$scabyt] Integer = [$intbyt] Hex = [$hexbyt] B +inary = [$binbyt] Binary String = [$binstr]\n"; print "Aborting Loop\n"; last; }

Results:

W:\Steve\PerlMonks>perl sopw-584100.pl Byte = [65] Integer = [65] Hex = [41] Binary = [01101100] Binary + String = [01101100] Aborting Loop

Same results using 'B8',
Last time I checked, Hex 41 should show binary 01000001.

What am I missing here?

Replies are listed 'Best First'.
Re: unpack Binary FAIL
by ikegami (Patriarch) on Aug 08, 2025 at 02:35 UTC

    You want unpack "B*" (not unpack "b*"), and it requires packed bytes.

    $ perl -Mv5.14 -e' my $scabyte = 0x41; say unpack "B*", pack "C*", $scabyte; ' 01000001

    When you already have unpacked bytes, you can use sprintf "%b".

    $ perl -Mv5.14 -e' my $scabyte = 0x41; say sprintf "%08b", $scabyte; ' 01000001

    #!/usr/bin/perl use v5.14; use warnings; my $packed_bytes = "ABCD"; my @bytes = unpack 'C*', $packed_bytes; my $bin = ''; for my $byte ( @bytes ) { printf "Decimal = [%1\$d] Hex = [%1\$02X] Binary = [%1\$08b]\n", $byte; $bin .= sprintf( "%08b", $byte ); } say ""; say $bin;
    Decimal = [65] Hex = [41] Binary = [01000001] Decimal = [66] Hex = [42] Binary = [01000010] Decimal = [67] Hex = [43] Binary = [01000011] Decimal = [68] Hex = [44] Binary = [01000100] 01000001010000100100001101000100

    #!/usr/bin/perl use v5.14; use warnings; my $packed_bytes = "ABCD"; my $bin = unpack "B*", $packed_bytes; say $bin;
    01000001010000100100001101000100

      Thank you! I suspected it would be a basic error -- wrong tool for the job.

Re: unpack Binary FAIL
by ysth (Canon) on Aug 10, 2025 at 20:26 UTC