Skip to content

Instantly share code, notes, and snippets.

@ig10
Created April 21, 2016 05:55
Show Gist options
  • Save ig10/4e72203ddfbecb1ac2b208d96447dcbf to your computer and use it in GitHub Desktop.
Save ig10/4e72203ddfbecb1ac2b208d96447dcbf to your computer and use it in GitHub Desktop.
Convert IPv4 to Binary numbers
octal, ipv4, input = [128, 64, 32, 16, 8, 4, 2, 1], [[],[],[],[]], nil
while input.nil? || input.split('.').size != 4 do
puts "Ingrese IPv4 a convertir"
input = gets.chomp
end
input = input.split('.').map(&:to_i)
ipv4.each_with_index do |binary_set, index|
total = input[index]
octal.each do |v|
fills = total > 0 && (total - v) >= 0
binary_set << (fills ? 1 : 0)
total -= v if fills
end
end
puts "El binario de tu IP es: \n #{ipv4.map{|x| x.join}.join(' ')}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment