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

Representing a 32-bit integer

by blankdon (Initiate)
on May 22, 2007 at 19:43 UTC ( [id://616850]=perlquestion: print w/replies, xml ) Need Help??

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

The problem is:

A function is to take a string containing an IP address, such as "192.168.11.5 <http://192.168.11.5/> ". Once it verifies that there's an IP address in the string, the function must produce and return a 32-bit integer representation.

$test1 = quadToInt("192.168.11.5 <http://192.168.11.5/> "); # $test1 would contain 3232238341.

The only way I know to get the representation is to use pack after replacing the '.'s with some numeric value like '0' i.e

# generate and return 32-bit integer representation of IP address $IPaddr =~ s/\./0/g; my $rep32bit = pack('N', "$IPaddr"); # unsigned long in 'network order +'

This returns 4294967295.
Question: how to get '3232238341' ?
Is there some other way in Perl to produce the 32-bit integer representation besides packing?

Edit: g0n - code tags and formatting

Replies are listed 'Best First'.
Re: Representing a 32-bit integer
by jettero (Monsignor) on May 22, 2007 at 19:48 UTC

    You want unpack, not pack, imo. Although, the document describing pack is a great deal more detailed. Also, see Socket for the inet_aton function, which is of great relevance here.

    use Socket; print "", unpack("N", inet_aton("192.168.11.5")), "\n";

    UPDATE: This has been amusing me for many minutes now (e.g. unpack("N", inet_aton("google.com"))). Thanks!

    1. http://1089054563/
    2. http://1109866011/

    -Paul

      Or unpack "N", pack "C4", split /\./, $IPaddr
Re: Representing a 32-bit integer
by NetWallah (Canon) on May 22, 2007 at 22:00 UTC
    To validate that the string you are given actually contains an IP address, you chould/should:
    use Regexp::Common qw /net/; if ($givenIP =~/^$RE{net}{IPv4}$/){ # got good IP. }

         "An undefined problem has an infinite number of solutions." - Robert A. Humphrey         "If you're not part of the solution, you're part of the precipitate." - Henry J. Tillman

Re: Representing a 32-bit integer
by Zaxo (Archbishop) on May 22, 2007 at 20:13 UTC

    You could torture vec into modifying integer representations, but why avoid pack/unpack? They're fast and made for the job.

    After Compline,
    Zaxo

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (4)
As of 2024-03-28 17:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found