Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 18 additions & 7 deletions lib/binary_to_decimal.rb
Original file line number Diff line number Diff line change
@@ -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)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This works, but can you do it without the Enumerable reverse method?

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)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

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
26 changes: 26 additions & 0 deletions test/binary_to_decimal_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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