Question

J'apprends Ruby et j'ai pensé créer un convertisseur binaire - décimal. Il obtient une chaîne binaire et convertit en équivalent décimal. Existe-t-il un moyen de garder une trace de l'étape d'itération en cours dans ruby ??afin que la variable 'x' puisse être supprimée?

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
Était-ce utile?

La solution

Oui, en utilisant la très puissante bibliothèque d'énumérateur:

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

Incidemment, Array # pack et String # unpack pourraient vous intéresser. Ils ont un support pour les chaînes de bits. De plus, un moyen encore plus simple d’obtenir ce résultat consiste à utiliser #to_i , par exemple. " 101 " .to_i (2) # = > 5

Autres conseils

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

Ou sur les versions antérieures à 1.8.7:

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

Pour les personnes (comme moi) qui ont trouvé cette réponse de Google,

Voici le moyen facile de convertir des fichiers binaires - > Décimale en rubis (et 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"
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top