Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

pack question

by dash2 (Hermit)
on Jul 05, 2001 at 19:21 UTC ( [id://94128]=perlquestion: print w/replies, xml ) Need Help??

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://94128]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (2)
As of 2024-04-25 20:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found