tags:

views:

383

answers:

2

I have a hex string (length 48 chars) that I want to convert to raw bytes with the pack function in order to put it in a Win32 vector of bytes.

How I can do this with Perl?

+1  A: 

The steps are:

  1. Extract pairs of hexadecimal characters from the string.
  2. Convert each pair to a decimal number.
  3. Pack the number as a byte.

For example:

use strict;
use warnings;

my $string = 'AA55FF0102040810204080';
my @hex    = ($string =~ /(..)/g);
my @dec    = map { hex($_) } @hex;
my @bytes  = map { pack('C', $_) } @dec;

Or, expressed more compactly:

use strict;
use warnings;

my $string = 'AA55FF0102040810204080';
my @bytes  = map { pack('C', hex($_)) } ($string =~ /(..)/g);
Michael Carman
Thanks how could i do the reverse operation from @bytes to string
ron
+8  A: 
my $bytes = pack "H*", $hex;

See perlpacktut for more information.

eugene y