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

Thanks for all the help in the CB but some requested code so here it goes. The bitwise conversion to network from dotted quad works correctly but the bitwise back to dotted quad fails. Below is the code.
sub dotted_quad_to_network { my ($dq_address) = @_; $dq_address =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/; return (($1 << 24) + ($2 << 16) + ($3 << 8) + $4); } sub network_to_dotted_quad { my ($address) = @_; return sprintf ("%d.%d.%d.%d", $address >> 24, ($address << 8) >> 24, ($address << 16) >> 24, ($address << 24) >> 24); }
In Perl version 5.8.6 this code works correctly giving the correct dotted quad from the network. In v5.8.8 it gives back a weird dotted quad that looks like this: 216.55333.14165328.3626324100. I am using this IP 216.37.80.132 to test with.

The Web is like a dominatrix. Everywhere I turn, I see little buttons ordering me to Submit. (Nytwind)
  • Comment on Converting between network and dotted quad. Issue with << and >> operators between Perl Versions.
  • Download Code

Replies are listed 'Best First'.
Re: Converting between network and dotted quad. Issue with << and >> operators between Perl Versions.
by zwon (Abbot) on Apr 13, 2009 at 17:34 UTC

    Perhaps your 5.8.8 uses 64bit integers. Try the following:

    sub network_to_dotted_quad { my ($address) = @_; return sprintf ("%d.%d.%d.%d", $address >> 24, ($address >> 16) & 255, ($address >>8) & 255, $address & 255); }
      zwon, thanks much! My sys admins just transferred our app to a new box and didn't tell me they installed 64bit. You were correct! Thanks again for your help!! Thanks to everyone for their input!

      The Web is like a dominatrix. Everywhere I turn, I see little buttons ordering me to Submit. (Nytwind)
        Like I mentioned in the CB, you reinvented inet_aton and inet_ntoa.
        use Socket qw( inet_aton inet_ntoa ); sub dotted_quad_to_network { return unpack 'N', inet_aton $_[0] } sub network_to_dotted_quad { return inet_ntoa pack 'N', $_[0] }