2010-11-26 7 views
0

Мне нужно преобразовать двоичный код 10100101 в целое число в C# без использования Convert.ToInt64 (bin, 2). Я работаю с микро-каркасом .net. Когда я использую int i = Convert.ToInt32(byt, 2); исключение создается с довольно unhelpfull сообщением:Преобразование двоичных данных в int без Convert.ToInt32

#### 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 
+0

Ну, что такое типовое e of `byt`? – Jon 2010-11-26 00:03:06

+1

Вы имеете в виду, что вам нужно преобразовать строку «10100101»? – 2010-11-26 00:05:04

+0

string byt = "10101001"; – UnkwnTech 2010-11-26 00:08:00

ответ

4

Чуть быстрее, чем вариант Femaref, так как она не требует надоедливых метода вызов, и использует OR вместо ADD просто для удовольствия:

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

Или еще аккуратнее:

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