用c#编程实现二进制转换为十进制
时间: 2024-09-21 22:12:40 浏览: 109
在 C# 中,你可以使用内置的 `Convert.ToInt32()` 或 `BitConverter.ToInt32()` 函数将二进制字符串转换成十进制整数。这里是一个简单的例子:
```csharp
public static int BinaryToDecimal(string binary)
{
// 验证输入是否只包含 '0' 和 '1'
if (!binary.All(char.IsDigit) || binary.Any(c => c != '0' && c != '1'))
throw new ArgumentException("Invalid binary input");
return Convert.ToInt32(binary, 2);
}
// 使用示例
string binaryString = "1010";
int decimalNumber = BinaryToDecimal(binaryString);
Console.WriteLine($"Binary {binaryString} equals decimal {decimalNumber}");
```
这个函数首先检查输入的二进制字符串是否有效,然后通过第二个参数2告诉`Convert.ToInt32()`这是一个二进制数。如果需要处理更复杂的二进制数据,比如从文件或网络接收,可以先读取到字节数组再进行转换。
阅读全文
相关推荐
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)