diff --git a/lib/binary_to_decimal.rb b/lib/binary_to_decimal.rb index 439e8c6..e88932b 100644 --- a/lib/binary_to_decimal.rb +++ b/lib/binary_to_decimal.rb @@ -5,5 +5,44 @@ # Calculate and return the decimal value for this binary number using # the algorithm you devised in class. def binary_to_decimal(binary_array) + power_num = 0 + index = -1 + decimal_array = [] + decimal_number = 0 + + binary_array.each do |num| + sum_of_nums = binary_array[index] * (2 ** power_num) + power_num += 1 + index -= 1 + + decimal_array << sum_of_nums + end + + decimal_array.each do |num| + decimal_number += num + end + return decimal_number raise NotImplementedError end + +def decimal_to_binary(decimal_number) + binary_array = [] + reversed_array = [] + index = -1 + + until decimal_number == 0 + if decimal_number % 2 == 0 + reversed_array << 0 + else + reversed_array << 1 + end + decimal_number /= 2 + end + + reversed_array.each do |num| + nums = reversed_array[index] + index -= 1 + binary_array << nums + end + return binary_array +end diff --git a/test/binary_to_decimal_test.rb b/test/binary_to_decimal_test.rb index ba17713..3395bb8 100644 --- a/test/binary_to_decimal_test.rb +++ b/test/binary_to_decimal_test.rb @@ -1,6 +1,6 @@ -require 'minitest/autorun' -require 'minitest/reporters' -require_relative '../lib/binary_to_decimal' +require "minitest/autorun" +require "minitest/reporters" +require_relative "../lib/binary_to_decimal" describe "binary to decimal" do it "From 10011001 to 153" do @@ -31,3 +31,20 @@ binary_to_decimal(binary_array).must_equal expected_decimal end end +describe "decimal to binary" do + it "Converts from 23 to 10111" do + decimal_number = 23 + expected_bin_array = [1, 0, 1, 1, 1] + decimal_to_binary(decimal_number).must_equal expected_bin_array + end + it "Converts from 108 to 1101100" do + decimal_number = 108 + expected_bin_array = [1, 1, 0, 1, 1, 0, 0] + decimal_to_binary(decimal_number).must_equal expected_bin_array + end + it "Converts from 1116 to 10001011100" do + decimal_number = 1116 + expected_bin_array = [1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0] + decimal_to_binary(decimal_number).must_equal expected_bin_array + end +end