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

Dear Monks

I have a question regarding the pack function.

$string = pack("H*",15); print "$string\n"; #prints some weird symbol print unpack("H*",$string),"\n"; #prints 15

If I try to print the packed string, what would I expect? How does this packed string associate with the value to be packed?

Thank you.

Replies are listed 'Best First'.
Re: print packed string
by Grimy (Pilgrim) on Jun 01, 2013 at 01:25 UTC

    A packed string is basically a base 256 integer. For example, the string 'AB' would represent the integer 65 + 66 * 256 (65 and 66 being the ASCII codes of A and B respectively).

    The H format asks pack to treat the next argument as an hexadecimal string. Since 15 is an integer, it is first converted to the string '15', which is then parsed as an hex-string, giving the number 21 (1 * 16 + 5). This number is then encoded in base 256, giving the character with ASCII code 21.

    pack('H*', 15) eq chr 21

    Since chr 21 isn't a printable character (it's actually Negative Acknowledge), it is rendered with this weird symbol you saw. This is largely system-dependant.

      Thank you Grimy.This is exactly what I want to know!

Re: print packed string
by johngg (Canon) on May 31, 2013 at 23:18 UTC

    I find that pack is easier to understand with code examples that pipe the packed string into hexdump. The last snippet is just packing the ASCII character set.

    $ perl -e 'print pack q{H*}, sprintf q{%2x}, 0x3a;' | hexdump -C 00000000 3a |:| 00000001
    $ perl -e ' print pack q{(H*)*}, map { sprintf q{%2x}, $_ } 0b111010, 072, 58, 0x3a;' | hexdump -C 00000000 3a 3a 3a 3a |::::| 00000004
    $ perl -e ' print pack q{(H*)*}, map { sprintf q{%2x}, $_ } 0 .. 127;' | hexdump -C 00000000 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f |......... +.......| 00000010 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f |......... +.......| 00000020 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f | !"#$%&'( +)*+,-./| 00000030 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e 3f |012345678 +9:;<=>?| 00000040 40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f |@ABCDEFGH +IJKLMNO| 00000050 50 51 52 53 54 55 56 57 58 59 5a 5b 5c 5d 5e 5f |PQRSTUVWX +YZ[\]^_| 00000060 60 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f |`abcdefgh +ijklmno| 00000070 70 71 72 73 74 75 76 77 78 79 7a 7b 7c 7d 7e 7f |pqrstuvwx +yz{|}~.| 00000080

    I hope that you also find these examples helpful.

    Cheers,

    JohnGG

Re: print packed string
by toolic (Bishop) on May 31, 2013 at 21:08 UTC