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

Mystified once again by the documentation on "pack" which makes my brain hurt.

What I want to do is convert a number like 324789 into a string representation which is shorter and more mnemonic than "324789". E.g., convert it into hex and print the ASCII chars for each octet (??) Is there a quick and elegant way to do this?

Dave

dave hj~

Replies are listed 'Best First'.
Re: pack question
by btrott (Parson) on Jul 05, 2001 at 19:41 UTC
    "Printing the ASCII chars" is not really equivalent to "converting to hex". Which do you want? :)

    If you want to print out 324789 as the binary representation of a long (in network order), for example, do this:

    print pack "N", 324789;
    Say instead that you want to print it out in hex; then you can do this:
    print unpack "H*", pack "N", 324789;
    Or you could use printf with the %x specifier.
Re: pack question
by jmcnamara (Monsignor) on Jul 05, 2001 at 20:11 UTC


    As btrott says, it isn't quite clear what you are after. Perhaps something like this:
    print hexdigits(324789), "\n"; sub hexdigits { join " ", map {sprintf "0x%02x", $_} unpack("C*", pack "V", $_ +[0]); } # Prints: 0xb5 0xf4 0x04 0x00
    Use pack "V" or "N" as required.

    John.
    --

Re: pack question
by Arguile (Hermit) on Jul 06, 2001 at 06:23 UTC
    I too was once mystifyed by pack, until I read Confession of a Perl Hacker. If you want to really understand the concept behind pack (painlessly) and how to use it effectively read through that discussion.