Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dotted decimal to hex 3

Status
Not open for further replies.
Jan 12, 2004
15
US
I am trying to convert dotted decimal strings
into their hex equivalent and vice versa...
For example
0.0.244.175.197.51 to
00.00.F4.AF.C5.33 or 0000f4afc533 or 00:00:F4:AF:C5:33

any ideas ? I know that you can print decimals
as hex with "%x"..

I am writing a perl program to map switch ports.
 
This produces the second of the example outputs you show above. You can vary the format string to get different outputs.
Code:
my $str = "0.0.244.175.197.51";
printf "%02x" x 6, split /\./, $str;


 
you could map that back to the original string like so, though there may be a more elegant way.
(It's late ...[sleeping])
Code:
my $str = "0.0.244.175.197.51";
my $x = sprintf "%02x" x 6, split /\./, $str;
print "\$x: $x\n";
[b]my $y = sprintf "%d." x 6, map {hex} $x=~ m|(..)|g;
print "\$y: $y\n";[/b]



 
You could also do something like:
Code:
my $str = '0.0.244.175.197.51';
# Dec To Hex
$str =~ s/([0-9]+)/sprintf("%02x", $1)/eg;
print $str, "\n";
# Hex to Dec
$str =~ s/(\w+)/hex($1)/eg;
print $str, "\n";
 
That is neat, elegant and readable; nice one.

Mike

shows ways to help with Tsunami Relief.

You cannot really appreciate Dilbert unless you've read it in the
original Klingon.

Want great answers to your Tek-Tips questions? Have a look at faq219-2884
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top