Skip to content

Instantly share code, notes, and snippets.

@KINGSABRI
Forked from bsingr/ruby_ipv4_notations.rb
Last active December 23, 2015 21:39
Show Gist options
  • Save KINGSABRI/6698170 to your computer and use it in GitHub Desktop.
Save KINGSABRI/6698170 to your computer and use it in GitHub Desktop.
# How to convert IPv4 addresses between integer <=> dot-decimal notation
INTEGER = 1698212032
DOT_DECIMAL = '192.168.56.101'
# [ 192, 168, 56, 101 ]
DOT_DECIMAL_PARTS = DOT_DECIMAL.split('.').map(&:to_i)
####################################
# integer to dot-decimal
####################################
# 1698212032 => '192.168.56.101'
puts "=== from INTEGER to DOT-DECIMAL ==="
# MANUALLY
number = INTEGER
p1 = (number) & 255 # 192
p2 = (number>>8) & 255 # 168
p3 = (number>>16) & 255 # 56
p4 = (number>>24) & 255 # 101
puts "MANU: #{p1}.#{p2}.#{p3}.#{p4}"
# AUTOMATICALLY
number = INTEGER
result = []
4.times do
# bitwise AND 255 bits
result.push number & 255
# bitwise SHIFT RIGHT 8 bits
number = number >> 8
end
puts "AUTO: #{result.join('.')}"
# You can Update Integer class it self
class Integer
def to_decimal
number = self
result = []
4.times do
result.push number & 255
number = number >> 8
end
result.join('.')
end
end
# Then
INTEGER.to_decimal # => 192.168.56.101
####################################
# dot-decimal to Integer
####################################
# '192.168.56.101' => 1698212032
puts "=== from DOT-DECIMAL to INTEGER ==="
# MANUALLY
parts = DOT_DECIMAL_PARTS
manually_int = parts[0] +
(parts[1] << 8) +
(parts[2] << 16) +
(parts[3] << 24)
puts "MANU: #{manually_int}"
# AUTOMATICALLY
number = DOT_DECIMAL
parts = DOT_DECIMAL_PARTS.dup
# sum up the integer beginning at 0
result = 4.times.inject(0) do |integer, index|
# take next part
part = parts.shift
# bitwise SHIFT LEFT
add = part << (8 * index)
# add to sum by returning it
integer += add
end
puts "AUTO: #{result}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment