Skip to content

Instantly share code, notes, and snippets.

@dgalarza
Created September 22, 2009 01:39
Show Gist options
  • Select an option

  • Save dgalarza/190723 to your computer and use it in GitHub Desktop.

Select an option

Save dgalarza/190723 to your computer and use it in GitHub Desktop.
# Generate 15 random IPs and convert them to Hexadecimal format,
# avoiding Ruby's built in conversion functions
#
# CSCI370 Assignment 1
#
# @author dgalarza (Damian Galarza)
# Create an array to represent hexadecimal numbers
@hexNumbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']
# A recursive method for converting a decimal number to hexadecimal notation
#
# @param {Int} Decimal Number
# @return hex representation
def convertHex(d)
remainder = d % 16
difference = d - remainder
## Check if we're done here
if difference == 0 then
result = @hexNumbers[remainder]
else
#other wise, get this digit and find the next
result = convertHex(difference / 16) + @hexNumbers[remainder]
end
#Return our result
result
end
# Loop through and generate 15 random IP numbers, converted to Hex
# when creating and IP address, we will generte each segment separately
for ips in 1..15
#store ips
decimal_ip = ""
hex_ip = ""
# Loop 4 times, creating a unique IP segment each time
for segment in 1..4
segment_num = 1 + rand(255)
#Store decimal representation of ip segment
decimal_ip += segment_num.to_s
#add the . seperator if we're not on the last segment
if segment != 4
decimal_ip += "."
end
#Update the hex representation of the ip
hex_ip += convertHex(segment_num)
end
#Print out the ip
puts decimal_ip + ' ' + hex_ip
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment