我需要将二进制10100101
转换为C#中的整数而不使用Convert.ToInt64(bin,2),我正在使用.net微框架。当我使用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
答案 0 :(得分: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;
}
您可能想要:
仅限LOL,这是一个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 :(得分: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);
}