Wednesday 19 November 2008

Converting Textual Data in a String to a Byte Array

What is the quickest and most efficient way of converting a string in VB6 to a byte array? This was a question I pondered recently when I saw various different ways of doing it, all of which turned out to be very inefficient.

First of all there is the most obvious way, loop through the string, character by character, converting each into its numerical character code and insert this into the byte array:

Dim strTemp As String Dim bytArray() As Byte Dim lngCount As Long ' If you have a string with a lot of data in it: strTemp = "Some long string..." ' This would be a very inefficient way ' of converting it to a byte array: ReDim bytArray(0 To Len(strTemp) - 1) For lngCount = 0 To Len(strTemp) - 1 bytArray(lngCount) = Asc(Mid(strTemp, lngCount + 1, 1)) Next

This is unfortunately very inefficient and I do not recommend you do it this way, ever. Even for very small strings.

Another way of doing it would be to instantiate the array by simply setting it to be equal to the string. The problem with this is that VB strings are always expressed as Unicode strings, therefore we would end up with a Unicode byte array and not an Ascii one.

If on the other hand you did want an Ascii byte array then you would have to remove the high byte from each character. Here is an example of how you could do this:

Dim strTemp As String Dim bytBuffer() As Byte Dim bytArray() As Byte Dim lngCount As Long strTemp = "Some long string..." ' Set a temporary array equal to the Unicode string. bytBuffer = strTemp ReDim bytArray(0 To Len(strTemp) - 1) For lngCount = 0 To UBound(bytBuffer) Step 2 ' Copy just the low byte of each character ' into the main byte array. bytArray(lngCount \ 2) = bytBuffer(lngCount) Next

Now this is much faster than the first method, however unless you have a specific need for a Unicode byte array (in which case you wouldn't need to copy the low byte of each character from a temporary array to the main array) there is an even faster and more reliable (and easier) way of converting a string to a byte array.

And that is to use the StrConv function:

bytArray = StrConv(strTemp, vbFromUnicode)

It's as simple as that. It's very easy, very reliable and very fast, you don't even need to initially dimension the array.

No comments: