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

my ($a,$b,$c,$d) = $address =~ /(\d+)\.(\d+)\.(\d+)\.(\d+)/;
my $hex_addr = sprintf "%02x.%02x.%02x.%02x", $a, $b, $c, $d;

Save yourself some typing and use an array :-)

my @bytes = $address =~ /(\d+)\.(\d+)\.(\d+)\.(\d+)/;
my $hex_addr = sprintf "%02x.%02x.%02x.%02x", @bytes;

Replies are listed 'Best First'.
Re: Re: Re: decimal -> hex
by bart (Canon) on Oct 12, 2002 at 10:12 UTC
    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.

      ...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
Re: Re: Re: decimal -> hex
by FireBird34 (Pilgrim) on Oct 11, 2002 at 16:05 UTC
    Ok, thanks all!