Question

Je dois convertir 10100101 binaire en un entier en C # sans utiliser Convert.ToInt64 (bin, 2), je travaille avec le cadre micro .net. Lorsque j'utilise int i = Convert.ToInt32(byt, 2); une exception est levée avec le message plutôt unhelpfull de:

 #### Exception System.ArgumentException - 0x00000000 (1) ####
    #### Message: 
    #### System.Convert::ToInt32 [IP: 000d] ####
    #### TRNG.Program::loop [IP: 0047] ####
    #### TRNG.Program::Main [IP: 0011] ####
A first chance exception of type 'System.ArgumentException' occurred in mscorlib.dll
An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll
Était-ce utile?

La solution

Un peu plus rapide que l'option de Femaref, car il ne nécessite pas une méthode de satanés appel, et les utilisations ou au lieu de ADD juste pour le plaisir:

public static int ParseBinary(string input)
{
    // Count up instead of down - it doesn't matter which way you do it
    int output = 0;
    for (int i = 0; i < input.Length; i++)
    {
        if (input[i] == '1')
        {
            output |= 1 << (input.Length - i - 1);
        }
    }
    return output;
}

Vous pouvez:

  • Vérifiez que la longueur est inférieure à 32 pour commencer
  • Vérifiez que chaque caractère est '0' ou '1'

Juste pour LOLs, voici une version LINQ:

public static int ParseBinary(string input)
{
    return input.Select((c, index) => new { c, index })
        .Aggregate(0, (current, z) => current | (z.c - '0') << 
                                        (input.Length - z.index - 1));
}

Ou encore plus net:

public static int ParseBinary(string input)
{
    return return input.Aggregate(0, (current, c) => (current << 1) | (c - '0'));
}

Autres conseils

string input = "10101001";
int output = 0;
for(int i = 7; i >= 0; i--)
{
  if(input[7-i] == '1')
    output += Math.Pow(2, i);
}

en général:

string input = "10101001";
int output = 0;
for(int i = (input.Length - 1); i >= 0; i--)
{
  if(input[input.Length - i] == '1')
    output += Math.Pow(2, i);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top