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
22 changes: 21 additions & 1 deletion lib/binary_to_decimal.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,25 @@
# 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
array = binary_array
power = 7

Choose a reason for hiding this comment

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

Minor: I suggest making 7 a constant or using binary_array.length -1 just to make things more flexible and avoid hardcoding randomish numbers.

decimal_value = 0
array.each do |bit|
decimal_value += bit * (2 ** power)
power -= 1
end
return decimal_value
#raise NotImplementedError
end

def decimal_to_binary(decimal_number)

Choose a reason for hiding this comment

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

This is actually reversing the binary digits, and your tests use numbers that read the same way backwards and forwards.

number = decimal_number
binary_num = []
while number > 1
mod = number % 2
binary_num.push(mod)
number = (number - mod)/2
end
binary_num.push(number)
return binary_num
end
29 changes: 21 additions & 8 deletions test/binary_to_decimal_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,41 @@
it "From 10011001 to 153" do
binary_array = [1, 0, 0, 1, 1, 0, 0, 1]
expected_decimal = 153

binary_to_decimal(binary_array).must_equal expected_decimal
end

it "From 00001101 to 13" do
binary_array = [0, 0, 0, 0, 1, 1, 0, 1]
expected_decimal = 13

binary_to_decimal(binary_array).must_equal expected_decimal
end

it "From 10000000 to 128" do
binary_array = [1, 0, 0, 0, 0, 0, 0, 0]
expected_decimal = 128

binary_to_decimal(binary_array).must_equal expected_decimal
end

it "From random binary to decimal" do
binary_array = Array.new(8) { rand(0..1) }
expected_decimal = binary_array.join.to_s.to_i(2)

binary_to_decimal(binary_array).must_equal expected_decimal
end
end

it "From 17 to 10001" do
decimal = 17
expected_binary = [1, 0, 0, 0, 1]
decimal_to_binary(decimal).must_equal expected_binary
end

it "From 45 to 101101" do
decimal = 45
expected_binary = [1, 0, 1, 1, 0, 1]
decimal_to_binary(decimal).must_equal expected_binary
end

end