Question

So, I want to convert a string to a dec value from this table: http://en.wikipedia.org/wiki/American_Standard_Code_for_Information_Interchange#ASCII-Table

For example, "hello" should be 104101108108111 then (h = 104, e = 101...). Well, I have to use a for-loop for this and I can't seem to get the error.

Private Function function1(text As String)
    Dim dec As String
    Dim i As Integer = 0

    For i = 0 To text.Length
        dec = dec & System.Text.ASCIIEncoding.ASCII.GetBytes(text)(i)
        i += 1
    Next
    Return dec
End Function

It works, but it gives me an error if the length of "text" is even (for example, text has got 2, 4, 6 or 8 letters). And when it's uneven (text has got 1, 3, 5, 7 letters), it only converts these uneven letters. So, just as an example. "hello" has got an uneven length (5 letters). So, it does not give me an error. Great! But, it only converts, the "h", the first "l" and the "o" into a dec.

Can anybody explain me why and how to fix this?

Was it helpful?

Solution

You are incrementing the count i in the loop. You don't need to do this in a For loop.

Also you are going past the end of the string. You need to end the loop at the Length - 1

Private Function function1(text As String) As String
    Dim dec As String = ""
    For i As Integer = 0 To text.Length - 1
        dec = dec & System.Text.ASCIIEncoding.ASCII.GetBytes(text)(i)
    Next
    Return dec
End Function

Note: switch option strict on - you will be glad you did in the long run!

OTHER TIPS

The loop increments itself, don't increment. It is a zero based array so a 14 length text is 0 to 13.

Private Function function1(text As String)
 Dim dec As String = ""
 For i As Integer = 0 To text.Length - 1
    dec = dec & System.Text.ASCIIEncoding.ASCII.GetBytes(text(i))(0)
    'i += 1 omit this part
 Next
 Return dec
End Function
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top