HWYDI: String Hex to Decimals April 22nd, 2008

How would You do it?!

I want to make a returning item out of these kinds of posts. I present a problem I had, and the way I solved it, and then you can tell how you did it (In the comments, in your own blog, ..).

I think this can be really interesting, since everyone has their own solution to problems, and nobody knows every possible way to solve something.

the Problem

At Openminds we generate a Virtual Server’s MAC Address by the IP the Virtual Server will get. So for example, host 88.151.243.8 will have MAC address 02:00:58:97:f3:08, where the last 4 parts are the hexadecimal representation of the IP address.

Calculating the IP to the MAC address is easy, but sometimes we want to know what IP address is linked to a certain mac. Most of the time we’ll get our mac addresses in the form of 0200.5897.f308, so we take this as our default input.

my Solution

#!/usr/bin/ruby
mac = ARGV[0] # => "0200.5897.f308"

if mac =~ /(\w{4})\.(\w{4})\.(\w{4})/
  ip = ($1 + $2 + $3).scan(/../)[-4..-1].collect do |hex|
    sprintf('%d', "0x#{hex}")
  end.join('.')
end

puts ip

How would You do it?

tags: l 2 comments »