Last active
December 27, 2015 15:39
-
-
Save missingno15/7349842 to your computer and use it in GitHub Desktop.
Script to help study and understand conversions from binary to decimal or decimal to binary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
puts | |
puts "Do CTRL+C at anytime to end the program.\nCoded by Kenneth Uy / missingno15" | |
#Option to study Binary→Decimal or Decimal→Binary | |
puts "\nPress 1 to study Binary→Decimal\nPress 2 to study Decimal→Binary" | |
print "> "; option = gets.chomp | |
#Checks to make sure that user input is only either 1 or 2 | |
until option == "1" || option == "2" | |
puts "\nSorry! Invalid option! Please try again!" | |
puts "\nPress 1 to study Binary→Decimal\nPress 2 to study Decimal→Binary" | |
print "> "; option = gets.chomp | |
end | |
if option == "1" | |
puts "\nBinary→Decimal initialized" | |
base2 = [0,1] | |
binary = "" | |
rand_digit = rand(1..8) | |
#Generates a binary number up to 8 digits | |
until binary.length == rand_digit | |
binary = binary + base2.sample.to_s | |
end | |
loop do | |
puts "\nWhat is #{binary} in decimal?" | |
print "> "; answer = gets.chomp | |
puts "The answer is #{binary.to_i(2)}.\n" | |
#Resets binary number | |
binary = "" | |
until binary.length == rand_digit | |
binary = binary + base2.sample.to_s | |
end | |
rand_digit = rand(1..8) #Resets random number of digits | |
end | |
else | |
puts "\nDecimal→Binary initialized" | |
#Generates random decimal number | |
decimal = rand(1..128) | |
loop do | |
puts "\nWhat is #{decimal} in binary?" | |
print "> "; answer = gets.chomp | |
puts "The answer is #{decimal.to_s(2)}.\n" | |
decimal = rand(1..256) # Resets binary number | |
end | |
end | |
################################################################################################### | |
# Links that helped me out: | |
# | |
# http://stackoverflow.com/questions/2339695/how-to-convert-a-string-or-integer-to-binary-in-ruby | |
# http://stackoverflow.com/questions/198460/how-to-get-a-random-number-in-ruby | |
# | |
################################################################################################### |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment