diff --git a/lib/binary_to_decimal.rb b/lib/binary_to_decimal.rb index 439e8c6..a80f067 100644 --- a/lib/binary_to_decimal.rb +++ b/lib/binary_to_decimal.rb @@ -1,9 +1,20 @@ -# A method named `binary_to_decimal` that receives as input an array of size 8. -# The array is randomly filled with 0’s and 1’s. -# The most significant bit is at index 0. -# The least significant bit is at index 7. -# Calculate and return the decimal value for this binary number using -# the algorithm you devised in class. def binary_to_decimal(binary_array) - raise NotImplementedError + decimal = 0 + binary_array.reverse.each_with_index do |bit, index| + unit = bit * 2 ** index + decimal += unit + end + return decimal +end + +def decimal_to_binary(decimal_number) + binary_value = [] + while decimal_number > 0 + binary_value << (decimal_number % 2) + decimal_number = (decimal_number / 2) + end + until binary_value.length == 8 + binary_value << 0 + end + return binary_value.reverse end diff --git a/test/binary_to_decimal_test.rb b/test/binary_to_decimal_test.rb index 18d4bb3..56cf90b 100644 --- a/test/binary_to_decimal_test.rb +++ b/test/binary_to_decimal_test.rb @@ -33,3 +33,29 @@ expect(binary_to_decimal(binary_array)).must_equal expected_decimal end end + +# my tests for decimal_to_binary + +describe "decimal to binary" do + it "From 162 to 10100010" do + decimal = 162 + expected_binary_array = [1, 0, 1, 0, 0, 0, 1, 0] + + expect(decimal_to_binary(decimal)).must_equal expected_binary_array + end + + it "From 26 to 00011010" do + decimal = 26 + expected_binary_array = [0, 0, 0, 1, 1, 0, 1, 0] + + expect(decimal_to_binary(decimal)).must_equal expected_binary_array + end + + it "From 207 to 11001111" do + decimal = 207 + expected_binary_array = [1, 1, 0, 0, 1, 1, 1, 1] + + expect(decimal_to_binary(decimal)).must_equal expected_binary_array + end + +end