Преобразовать двоичный для Int без конвертации .Toint32

StackOverflow https://stackoverflow.com/questions/4281649

  •  28-09-2019
  •  | 
  •  

Вопрос

Мне нужно преобразовать двоичный 10100101 В целое число в C # без использования Converty.Toint64 (Bin, 2), я работаю с .NET Micro Framework. Когда я использую int i = Convert.ToInt32(byt, 2); Исключение брошено с скорее разнесенным посланием:

 #### 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
Это было полезно?

Решение

Слегка быстрее, чем вариант FEMAREF, так как он не требует вызова надоемого метода, и использует или вместо добавления только для удовольствия:

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;
}

Вы можете захотеть:

  • Убедитесь, что длина меньше 32, чтобы начать с
  • Убедитесь, что каждый символ «0» или «1»

Просто для LOLS, вот версия 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));
}

Или Neater еще:

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

Другие советы

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

В основном:

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);
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top