Question

I am learning Ruby and thought of making a Binary->Decimal converter. It gets a binary string and converts to decimal equivalent. Is there a way to keep track of the current iteration step in ruby so that the variable 'x' can be removed?

def convert(binary_string)
    decimal_equivalent = 0
    x=0   
    binary_string.reverse.each_char do |binary|
      decimal_equivalent += binary.to_i * (2 ** x)
    x+=1
    end

   return decimal_equivalent
end
Was it helpful?

Solution

Yes, by using the very powerful enumerator library:

require 'enumerator'
def convert(binary_string)
  decimal_equivalent = 0
  binary_string.reverse.enum_for(:each_char).each_with_index do |binary, i|
    decimal_equivalent += binary.to_i * (2 ** i)
  end
  return decimal_equivalent
end

Incidentally, you may be interested in Array#pack, and String#unpack. They have support for bit strings. Also, an even easier way to get this result is to use #to_i, e.g. "101".to_i(2) #=> 5

OTHER TIPS

binary_string.reverse.chars.each_with_index do |binary, i|
  decimal_equivalent += binary.to_i * (2 ** i)
end

Or on versions older than 1.8.7:

binary_string.reverse.split(//).each_with_index do |binary, i|
  decimal_equivalent += binary.to_i * (2 ** i)
end

For the people (like me) who found this answer from google,

Here's the easy way to convert binary -> decimal in ruby (and back again):

# The String.to_i function can take an argument indicating
# the base of the number represented by the string.
decimal = '1011'.to_i(2)
# => 11

# Likewise, when converting a decimal number, 
# you can provide the base to the to_s function.
binary  = 25.to_s(2)
# => "11001"

# And you can pad the result using right-justify:
binary  = 25.to_s(2).rjust(8, '0')
# => "00011001"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top