Created
March 28, 2021 15:25
-
-
Save 0rbianta/126f59903f62000f5aff5518c5165653 to your computer and use it in GitHub Desktop.
Binary converter free 2.0 with Ruby
This file contains hidden or 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
def num2bin(num) | |
build_reverse = "" | |
eax = num | |
while eax != 0 | |
build_reverse += (eax%2).to_s | |
eax = eax/2.to_i | |
end | |
return build_reverse.reverse | |
end | |
def bin2num(bin) | |
build = 0 | |
for idx in (0...bin.to_s.size) | |
idx_r = bin.to_s.size-idx-1 | |
pchar = bin.to_s[idx_r].to_i | |
build += pchar * 2**idx | |
end | |
return build | |
end | |
def main() | |
puts "Welcome to Ruby Binary converter by 0rbianta" | |
puts "SELECT AN OPTION: \n1)DEC2BIN\n2)BIN2DEC\n3)Exit\n\n" | |
print("USER>> ") | |
usr_select = gets.chomp | |
case usr_select | |
when "1" | |
print("USER>> ") | |
usr = gets.chomp | |
bin = num2bin(usr.to_i) | |
puts "OUTPUT: "+bin | |
when "2" | |
print("USER>> ") | |
usr = gets.chomp | |
num = bin2num(usr) | |
puts "OUTPUT: "+num.to_s | |
when "3" | |
exit() | |
else | |
puts "Unknown option selected. Exiting..." | |
exit() | |
end | |
end | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment