Reputation: 23
My function converts an input binary number into its decimal equivalent. However, when I enter 110 instead of getting 6 ([2^2 * 1, 2^1 * 1, 2^0 * 0]
⇒ [4 + 2 + 0]
⇒ 6
) I get 7 because the last value in the Array is changed to 1. ([1, 1, 0]
⇒ [1, 1, 1]
). This happens when I save the value at that index using .to_i
to valueInt
. At the same time, however, there is an if
statement that should prevent anything being done to an element with a 0 in it. I am stumped.
puts "BinaryArr: #{binaryArr}"
# loops through the array in reverse order and converts the 1's
# to their respective weight by location
binaryArr.reverse.each_index do |index|
if binaryArr[index] != 0 then
valueInt = binaryArr[index].to_i
puts "ValueInt: #{valueInt}"
val = (2**index)*valueInt
puts "val: #{val}"
binaryArr[(binaryArr.length - 1) - index] = "#{val}"
end
end
puts "WeightArr: #{binaryArr}"
# loops through the arr adding the elements together for the total (decimal value)
decimalInt = 0
binaryArr.each_index do |x|
thisVal = binaryArr[x].to_i
decimalInt += thisVal
if binaryArr[x + 1] == nil then
break
end
end
puts "Decimal Value: #{decimalInt}"
THE OUTPUT: when 110 is input
Binary is: 3 Bits long
BinaryArr: ["1", "1", "0"]
ValueInt: 1 <== why is this a 1 instead of a 0!?!?
val: 1
ValueInt: 1
val: 2
ValueInt: 1
val: 4
WeightArr: ["4", "2", "1"]
Decimal Value: 7
Upvotes: 2
Views: 64
Reputation: 1668
You are indexing the binaryArr
inside the loop binaryArr.reverse.each_index do
... end
to get the value valueInt
, but you should be indexing the reverse
. You can set the reverse
in a variable like this reverseArr = binaryArr.reverse
before the loop and make sure you iterate over reverseArr
and indexing it inside the loop. For example:
puts "BinaryArr: #{binaryArr}"
reverseArr = binaryArr.reverse
# lops through the array in reverse order and converts the 1's
# to there respective weight by location
reverseArr.each_index do |index|
valueInt = reverseArr[index].to_i
puts "ValueInt: #{valueInt}"
val = (2**index)*valueInt
puts "val: #{val}"
binaryArr[(binaryArr.length-1)-index] = "#{val}"
end
puts "WeightArr: #{binaryArr}"
# loops through the arr adding the elements together for the total(decimal value)
decimalInt = 0
binaryArr.each_index do |x|
thisVal = binaryArr[x].to_i
decimalInt += thisVal
if binaryArr[x+1]==nil then
break
end
end
puts "Decimal Value: #{decimalInt}"
Of course, you can remove this line: if binaryArr[index]!=0 then
... end
Upvotes: 2
Reputation: 80065
if binaryArr[index]!=0 then
According to the output binaryArr
contains strings. "a_string" != 0 will aways be true.0**0
is 1.Upvotes: 0