tags:

views:

252

answers:

1

I've been using the ip-address gem and it doesn't seem to have the ability to convert from a netmask of the form

255.255.255.0

into the CIDR form

/24

Does anyone have an ideas how to quickly convert the former to the latter ?

+5  A: 

Here is the quick and dirty way

require 'ipaddr'
puts IPAddr.new("255.255.255.0").to_i.to_s(2).count("1")

There should be proper function for that, I couldn't find that, so I just count "1"

If you're going to be using the function in a number of places and don't mind monkeypatching, this could help:

IPAddr.class_eval
  def to_cidr
    "/" + self.to_i.to_s(2).count("1")
  end
end

Then you get

IPAddr.new('255.255.255.0').to_cidr
# => "/24"
S.Mark
I'm not sure that there's anything more proper than using count("1"). Perhaps something like this? `32 - (2**32 - 1 - IPAddr.new("255.255.255.0").to_i).to_s(2).length`
Chuck Vose
In C, I will probably do shifting to right, and test with unsigned int ipaddr=0xFFFFFF00;while(ipaddrbits--;}` for the above case, only need to shift right 8 times I think.
S.Mark