in reply to decimal -> hex

my $address = "127.0.0.1"; # from decimal to hex: my ($a,$b,$c,$d) = $address =~ /(\d+)\.(\d+)\.(\d+)\.(\d+)/; my $hex_addr = sprintf "%02x.%02x.%02x.%02x", $a, $b, $c, $d; print "[$hex_addr]\n"; #prints "[7f.00.00.01]"; # from hex to decimal: my ($a, $b, $c, $d) = $hex_addr =~ /(\w+)\.(\w+)\.(\w+)\.(\w+)/; my $addr = hex($a). "." . hex($b) . "." . hex($c) . "." . hex($d); print "[$addr]\n"; #prints "[127.0.0.1]"

Hope it helps.

jarich

Update: Added the second part once I worked it out, but kabel beat me anyway.

Replies are listed 'Best First'.
Re: Re: decimal -> hex
by grantm (Parson) on Oct 11, 2002 at 07:18 UTC
    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;
    
      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.

      Ok, thanks all!