Reputation: 701
I'm trying to implement my own method of converting binary to decimal and I'm following the following example of calculating the decimal value of the binary string 101
:
101 => 1*2^2 + 0*2^1 + 1*2^0 => 1*4 + 0*2 + 1*1 => 4 + 1 => 5
My method is
def to_decimal binary
num_array = binary.to_s.split('').map(&:to_i)
puts num_array.inject { |dec, num| dec + num * 2**(num_array.length-1) }
end
This seems to work fine for 1001
which gives 9
but 100
gives 1
and 11010
gives 33
when it should be giving 26. I've tried to look this up but I've found a few different ways to going about this and they're just confusing me even further.
Upvotes: 1
Views: 88
Reputation: 6545
Instead of this:
num_array.inject{ |dec, num| dec + num * 2**(num_array.length-1) }
You meant this (multiplying by current power, and building decimal from the lowest to the highest power):
num_array.reverse!
num_array.each_index.inject(0){ |dec, index| dec + num_array[index] * 2**index }
Upvotes: 2