Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save harrisonmalone/184e7e0123d39d22abf51ff601b57adb to your computer and use it in GitHub Desktop.

Select an option

Save harrisonmalone/184e7e0123d39d22abf51ff601b57adb to your computer and use it in GitHub Desktop.
# 1. Make a ruby method that takes a number in base 2 (binary, as a string) and converts it to a decimal (not using the inbuilt ruby methods).
def binary_to_decimal(binary)
binary = binary.split("").map(&:to_i)
# this splits binary numbers into an array and turns them into integers
exp = binary.length - 1
# => 5
# this determines the starting point of the exponential, we have to minus 1 to get the correct exp, we need the last exp to be 2 ** 0
base_array = []
while exp >= 0
# while 5 is greater than or equal to 0 do this, we need to do the 0 as we need the last base to be 1, when exp gets to -1 the while loop stops
base = 2 ** exp
# we start with 2 to the power of 5
# => 32
base_array << base
exp -= 1
end
# this gets me a base_array, each item in this array correlates with each item in the binary array
# => [32, 16, 8, 4, 2, 1]
index = 0
exp = binary.length
# we reset the exp, we don't need to add anything this time
results = []
while index < exp
if binary[index] == 1
# if the binary index is equal to one that means it takes the to the power of value
results << base_array[index]
end
index += 1
end
# sum the array with the base_array values in it
return results.sum
end
p binary_to_decimal("001100")
# 2. Make a ruby method that takes a number in decimal (base 10, as an integer), and converts it to base 2 (binary - which will have to be a string).
def decimal_to_binary(decimal)
decimal = decimal.to_i
# we need to turn decimal to an integer so we can do math on it
binary = []
while decimal > 0
result = decimal % 2
# this returns either 1 or 0 remainders for each decimal, the decimal is changed in each while cycle below
binary << result
decimal = (decimal / 2.0).floor
# this math concept comes from this https://www.wikihow.com/Convert-from-Decimal-to-Binary example where you continue to divide by 2 until you reach 0
end
# the array comes back in the reverse order so we just do a simple .reverse to make it perfect
return binary.reverse.join
end
p decimal_to_binary("10002223")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment