in reply to Re: Re: decimal -> hex
in thread decimal -> hex

Save yourself some typing and use an array :-)
my @bytes = $address =~ /(\d+)\.(\d+)\.(\d+)\.(\d+)/; my $hex_addr = sprintf "%02x.%02x.%02x.%02x", @bytes;
Save yourself even more typing and make one expression of it.
my $hex_addr = sprintf "%02x.%02x.%02x.%02x", $address =~ /(\d+)\.(\d+ +)\.(\d+)\.(\d+)/;
As you seem to be absolutely sure on the address format, split() will do:
my $hex_addr = sprintf "%02x.%02x.%02x.%02x", split /\./, $address;
I'm sure others would recommend use of inet_aton(), from Socket.pm, because it's more flexible in what it accepts for an IP address. Unfortunately for us, if produces a string of 4 packed bytes, but it's nothing unpack() can't easily handle.
use Socket; my $address = '127.1'; my $hex_addr = sprintf "%02x.%02x.%02x.%02x", unpack 'C*', inet_aton($ +address);
And if you prefer uppercase hex instead of lowercase, use '%02X' instead of '%02x' in the sprintf() template.

Replies are listed 'Best First'.
Re: Re: Re: Re: decimal -> hex
by Anonymous Monk on Oct 13, 2002 at 07:27 UTC

    ...and slightly shorter|more extensible (if perhaps less efficient) way:

    my $hex_addr=join '.',map {sprintf "%02x",$_} split /\./,$address;

    Or even:

    (my $hex_addr=$address)=~s/(\d+)/sprintf("%02x",$1)/gx;

    ...although of course the results could be a bit funny if it's not an IP address.

      Curses! I got distracted by the coolness of /x. I meant of course (particularly given the context):

      (my $hex_addr=$address)=~s/(\d+)/sprintf("%x",$1)/ge