简体   繁体   中英

Convert Binary To Decimal Using Array and Loop

I am trying to write a VB function that converts binary to decimal. I need to store the binary length in an array and use a loop to find my answer. I have been trying to figure this out for a while. This is what I have so far maybe you can help.

Public Function binaryToDecimal(ByVal Binary As String)
    Dim myDecimal As Integer
    Dim blength As Integer = Binary.Length
    Dim index(blength) As Integer
    For index = index To 0 Step -1
        myDecimal += Binary * (2 ^ (blength - 1))
        blength = blength - 1
    Next
    Return myDecimal
End Function

I don't understand your code at all... You never even fill the array with anything. Neither do you do anything if the binary string contains zeros ( 0 ).

But if you want to convert binary to decimal, here's a simple approach (and you don't really need an array):

Public Function BinaryToDecimal(ByVal Binary As String) As Integer
    Dim ReturnValue As Integer = 0
    Dim x As Integer = 1
    For i = Binary.Length - 1 To 0 Step -1
        If Binary.Chars(i) = "1"c Then
            ReturnValue += x
        End If
        x += x
    Next
    Return ReturnValue
End Function

The function starts at the end of the string and goes backwards. It increments x by itself for every char, and ReturnValue is incremented by the current x if the current character is '1'.

The function will convert for example 1111 into 15 , 100000 into 32 , and 1011101001 into 745 .

Tested: http://ideone.com/SsZ3d2

Hope this helps!


EDIT:

It's also worth mentioning that the function does not support spaces in the string. If you want it to do that, just tell me and I'll add that too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM