Honorable Monks,

An application reads binary data from an external system, and saves it using $h = unpack("H*", $b). If I try to reconstruct the binary data with $b = pack("H*", $h), the binary data will sometimes have a trailing null byte. Is it possible to make sure the binary data as it were (i.e. never add the null byte)?

A little code sample to illustrate the problem indicates that is works when input length is even only:
$ cat pack.t use strict; use warnings; use Test::More qw /no_plan/; my @arr = (0 .. 9, 'a' .. 'f'); my $hexdata = q{}; while (@arr) { $hexdata .= shift @arr; my $binary_data = pack("H*", $hexdata); cmp_ok(unpack('H*', $binary_data), 'eq', $hexdata); } __END__ $ perl pack.t not ok 1 # Failed test at pack.t line 11. # got: '00' # expected: '0' ok 2 not ok 3 # Failed test at pack.t line 11. # got: '0120' # expected: '012' ok 4 not ok 5 # Failed test at pack.t line 11. # got: '012340' # expected: '01234' ok 6 not ok 7 # Failed test at pack.t line 11. # got: '01234560' # expected: '0123456' ok 8 not ok 9 # Failed test at pack.t line 11. # got: '0123456780' # expected: '012345678' ok 10 not ok 11 # Failed test at pack.t line 11. # got: '0123456789a0' # expected: '0123456789a' ok 12 not ok 13 # Failed test at pack.t line 11. # got: '0123456789abc0' # expected: '0123456789abc' ok 14 not ok 15 # Failed test at pack.t line 11. # got: '0123456789abcde0' # expected: '0123456789abcde' ok 16 1..16 # Looks like you failed 8 tests of 16.
--
No matter how great and destructive your problems may seem now, remember, you've probably only seen the tip of them. [1]

In reply to Reconstruct binary data saved with unpack("H*", $b) by andreas1234567

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.