vb二进制转十进制代码
以下是VB.NET中将二进制转换为十进制的代码:
Public Function BinaryToDecimal(ByVal binary As String) As Integer
Dim decimalValue As Integer = 0
Dim power As Integer = 0
For i As Integer = binary.Length - 1 To 0 Step -1
If binary(i) = "1" Then
decimalValue += 2 ^ power
End If
power += 1
Next
Return decimalValue
End Function
使用示例:
Dim binaryValue As String = "101010"
Dim decimalValue As Integer = BinaryToDecimal(binaryValue)
Console.WriteLine(decimalValue) '输出42
以下是VB.NET中将二进制转换为十进制的完整代码:
Public Function BinaryToDecimal(ByVal binary As String) As Integer
Dim decimalValue As Integer = 0
Dim power As Integer = 0
For i As Integer = binary.Length - 1 To 0 Step -1
If binary(i) = "1" Then
decimalValue += 2 ^ power
End If
power += 1
Next
Return decimalValue
End Function
'使用示例:
Dim binaryValue As String = "101010"
Dim decimalValue As Integer = BinaryToDecimal(binaryValue)
Console.WriteLine(decimalValue) '输出42
这个函数接受一个二进制字符串作为参数,并将其转换为十进制整数。它使用一个循环来遍历二进制字符串中的每个位,并根据位的值计算出对应的十进制值。最后,它返回计算出的十进制值。