How to convert 48th sixth string to bytes using Perl?

I have a hexadecimal string (48 characters long) that I want to convert to raw bytes using the pack function to put it in a Win32 byte vector.

How can I do this with Perl?

+5
source share
3 answers

Steps:

  • Extract pairs of hexadecimal characters from a string.
  • Convert each pair to a decimal number.
  • Set the number as a byte.

For instance:

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);
+4
source
my $bytes = pack "H*", $hex;

See perlpacktut for details .

+21
source

:

"61 62 63 64 65 67 69 69 6a"

, ASCII ( "abcdefghij" ).

- :

$ echo "61 62 63 64 65 67 69 69 6a" | perl -ne 'print "$_"; print pack("H2 "x10, $_)."\n";'
61 62 63 64 65 67 69 69 6a
a

... , :)

-, , , , ​​ , :

$ echo -n "61 62 63 64 65 67 68 69 6a" | hexdump -C
00000000  36 31 20 36 32 20 36 33  20 36 34 20 36 35 20 36  |61 62 63 64 65 6|
00000010  37 20 36 38 20 36 39 20  36 61                    |7 68 69 6a|
0000001a

_ ( NB: , "" , , hexdump:

$ echo -n "abcdefghij" | hexdump -C
00000000  61 62 63 64 65 66 67 68  69 6a                    |abcdefghij|
0000000a

... . ) _

, Pack/Unpack Tutorial (AKA How System ) , :

pack [...]

$rec = pack( "l i Z32 s2", time, $emp_id, $item, $quan, $urgent);

, , , [...]

$rec ( , , , ). .

    Offset   Contents (increasing addresses left to right)
         0   160  44  19  62| 41  82   3   0| 98 111 120 101 115  32 111 102
              A0  2C  13  3E| 29  52  03  00| 62  6f  78  65  73  20  6f  66
                                            |  b   o   x   e   s       o   f

, $_ - , pack "" ( ); "" ( , , !). , "" ASCII , ( , ).

, $_, split - :

$ echo "61 62 63 64 65 67 68 69 6a" | perl -ne 'print "$_"; print pack("H2", split(/ /, $_))."\n";'
61 62 63 64 65 67 68 69 6a
a

... pack ed ( ); :

$ echo "61 62 63 64 65 67 68 69 6a" | perl -ne 'print "$_"; print pack("H2"x10, split(/ /, $_))."\n";'
61 62 63 64 65 67 68 69 6a
abcdeghij

$ echo "61 62 63 64 65 67 68 69 6a" | perl -ne 'print "$_"; print pack("(H2)*", split(/ /, $_))."\n";'
61 62 63 64 65 67 68 69 6a
abcdeghij
+1
source