Pergunta

Estou aprendendo Ruby e pensou em fazer um conversor Binary-> Decimal. Ela recebe uma string binária e convertidos para decimal equivalente. Existe uma maneira de manter o controle da etapa de iteração atual em Ruby para que a variável 'x' pode ser removido?

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
Foi útil?

Solução

Sim, usando a biblioteca recenseador muito poderosa:

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

A propósito, você pode estar interessado em Array#pack e String#unpack. Eles têm suporte para cadeias de bits. Além disso, uma forma ainda mais fácil de obter este resultado é usar #to_i, por exemplo, "101".to_i(2) #=> 5

Outras dicas

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

Ou em versões mais antigas do que 1.8.7:

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

Para as pessoas (como eu) que encontraram esta resposta do Google,

Aqui é a maneira fácil de binário convertido -> decimal em ruby ??(e vice-versa):

# 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"
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top