Hugh Janus wrote:
I am using the below functions in order to convert strings to bytes and
vice versa. I totally ans shamefully stole these functions from this
group btw! Anyway, they work great but as sooooo slow.
<snip>
Private Function ArrayToString(ByVal bytes() As Byte, Optional ByVal
format As String = Nothing) As String
<snip>
>Private Function StringToArray(ByVal s As String, Optional ByVal
style As System.Globalization.NumberStyles = Nothing) As Byte()
<snip>
To what Herfried K. Wagner [MVP] responded:
<snip>
Why not use
'System.Text.Encoding.GetString'/'System.Text.Encoding.GetBytes'?
It seems the OP is trying something different. In other words, given a
byte sequence of, say {100, 120, 200, 1, 2, ...}, the OP needs to
convert it to the string "100,120,200..." and, eventually, back again
to bytes.
The original methods seem ok to me. If you want to speed them up,
though, maybe you'll have to let go the formatting parameters and live
with more simplistic functions. A possible (and radical) approach could
be:
<code>
Function FromString(ByVal Source As String) As Byte()
'converts a string in the format "123,211,0,45...",
'to an array of bytes {123, 211, 0, 45,...}
If Source Is Nothing OrElse Source.Length = 0 Then
Return New Byte() {}
End If
'Counts the number of ","
'to find the number of bytes to convert
'(!)
Dim Count As Integer = 1
For Each C As Char In Source
If C = ","c Then Count += 1
Next
Dim Bytes(0 To Count - 1) As Byte
Dim AscZero As Integer = Asc("0"c)
Dim Value As Byte
Dim Index As Integer
For Each C As Char In Source
'Converts each char to the corresponding byte value
If C <","c Then
Value = CByte(Value * 10 + (Asc(C) - AscZero))
Else
Bytes(Index) = Value
Index += 1
Value = 0
End If
Next
'Saves the last value
Bytes(Index) = Value
Return Bytes
End Function
Function FromBytes(ByVal Source() As Byte) As String
'Converts an array of bytes in a string in the format
'"123,211,0,45...", where 123, 211, 0, etc are the
'bytes from the array
If Source Is Nothing OrElse Source.Length = 0 Then
Return String.Empty
End If
'Assumes each number occupies 3 digits and is comma
'separated. We probably will need less space than this
Dim Chars(0 To Source.Length * 4 - 1) As Char
'Starts from the end of the array
Dim Index As Integer = Chars.Length - 1
Dim AscZero As Integer = Asc("0"c)
'Saves the converted chars from the end to the
'begining of the string
For P As Integer = Source.Length - 1 To 0 Step -1
Dim B As Integer = Source(P)
If B <0 Then
'Manually converts B to string, from right
'to left (i.e. less significant digits first)
Do While B 0
Chars(Index) = Chr(AscZero + B Mod 10)
B \= 10
Index -= 1
Loop
Else
Chars(Index) = "0"c
Index -= 1
End If
Chars(Index) = ","c
Index -= 1
Next
'Advances Index to point to the first digit
Index += 2
Return New String(Chars, Index, Chars.Length - Index)
End Function
</code>
HTH
Regards,
Branco.