perlpackunpack

Unable to get Perl's pack() to work in this case


I ran the following code:

$a = pack("H1H3", "1", "abc");
$b = unpack("B*", $a);
print "Got $b \n";

Execute:

cd C:\Users\a0875499\Documents
perl abc.pl

Output:

Got 000100001010101111000000

The output looks incorrect to me. There is an extra "0000" which shouldn't be present. I am looking for the output to be "0001101010111100". Do you know what I am missing?


Solution

  • The 'H' format for pack() assembles bytes, so if you supply an odd number of values it will pad out the last byte with a null nybble.

    If I correctly understand what you want to achieve, you could do it with:

    $a = pack("H4", "1abc");
    

    or

    $a = pack("H*", "1abc");