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

Fellow monks,

I know this should be simple, but I am having a mental block for the last half hour. I need to take a variable length ascii string and convert it to the appropriate number of bytes. As an example, the string "0x0102" should become two bytes where the MSB byte is 0x01 and LSB byte is 0x02. I know this should be doable with a pack() call, but I can't seem to get it. Here's what I have so far:

use strict; use warnings; my $string = "0x010203"; my @in = split(//, $string); shift @in; shift @in; my $bytes = int(scalar(@in) / 2); my $output = pack('H2' x $bytes, @in); # print out the converted output, just to double check print unpack ('H2' x $bytes, $output); $output =~ s/[\x00-\x1F\xFF]/./g; # ASCII representation of hex value +of byte print " $output\n"; # ASCII character for each byte
which produces the right number of bytes, but with the wrong value of "001000 ...".

Thanks for the help!

Replies are listed 'Best First'.
Re: converting ASCII hex into binary
by BrowserUk (Patriarch) on Apr 28, 2006 at 00:50 UTC

    my $s = '0x010203';; ## Skip over the '0x' and extract the next 4 bytes ## then pack those 4 hex characters to binary my $bin = pack 'H*', unpack 'xxA4', $s;; ## unpack the binary back to hex to check it worked. print unpack 'H*', $bin;; 0102

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: converting ASCII hex into binary
by davidrw (Prior) on Apr 28, 2006 at 00:17 UTC
    I think the problem is just in @in and not the pack/unpack .. When you pack @in in H2's, it's ('0','1','0','2','0','3') ... I hardcoded it as ('01', '02', '03') in a test run and it gave your desired output..

    Probably not the best way, but this works:
    my @in = grep length $_, split(/(..)/, $string); shift @in; # just 1 shift to pull off '0x' my $bytes = scalar(@in); # no longer need the div by 2
Re: converting ASCII hex into binary
by ikegami (Patriarch) on Apr 28, 2006 at 02:36 UTC
    As an example, the string "0x0102" should become two bytes where the MSB byte is 0x01 and LSB byte is 0x02
    $string =~ '0x0102'; $output = hex($string); print($output); # 258 (0x0102)

    Or did you want "\x01\x02":

    $string =~ '0x0102'; $output = pack('H*', substr($string, 2)); print($output); # "\x01\x02"