1. Pure VB6 UTF8_Encode function:
Function UTF8_Encode(ByVal sStr As String) Dim i As Integer Dim thisChar As String Dim sUtf8 As String For i = 1 To Len(sStr) thisChar = AscW(Mid(sStr, i, 1)) If thisChar < 128 Then sUtf8 = sUtf8 + Mid(sStr, i, 1) ElseIf ((thisChar > 127) And (thisChar < 2048)) Then sUtf8 = sUtf8 + Chr(((thisChar \ 64) Or 192)) sUtf8 = sUtf8 + Chr(((thisChar And 63) Or 128)) Else sUtf8 = sUtf8 + Chr(((thisChar \ 144) Or 234)) sUtf8 = sUtf8 + Chr((((thisChar \ 64) And 63) Or 128)) sUtf8 = sUtf8 + Chr(((thisChar And 63) Or 128)) End If Next i UTF8_Encode = sUtf8 End Function
2. VB6: How To Convert UTF-8 Byte Arrays into Unicode Strings (and vice versa)
For this code to work, you will need to add a reference to the Microsoft ActiveX Data Objects 2.5 Library later versions of this library will also work.
The first function converts a unicode string to a byte array:
|
| ' accept a byte array containing utf-8 data
' and convert it to a string
Public Function ConvertStringToUtf8Bytes(ByRef strText As String) As Byte()
Dim objStream As ADODB.Stream
Dim data() As Byte
' init stream
Set objStream = New ADODB.Stream
objStream.Charset = "utf-8"
objStream.Mode = adModeReadWrite
objStream.Type = adTypeText
objStream.Open
' write bytes into stream
objStream.WriteText strText
objStream.Flush
' rewind stream and read text
objStream.Position = 0
objStream.Type = adTypeBinary
objStream.Read 3 ' skip first 3 bytes as this is the utf-8 marker
data = objStream.Read()
' close up and return
objStream.Close
ConvertStringToUtf8Bytes = data
End Function
This second function does the opposite, converting a byte array into a unicode string:
' accept a byte array containing utf-8 data
' and convert it to a string
Public Function ConvertUtf8BytesToString(ByRef data() As Byte) As String
Dim objStream As ADODB.Stream
Dim strTmp As String
' init stream
Set objStream = New ADODB.Stream
objStream.Charset = "utf-8"
objStream.Mode = adModeReadWrite
objStream.Type = adTypeBinary
objStream.Open
' write bytes into stream
objStream.Write data
objStream.Flush
' rewind stream and read text
objStream.Position = 0
objStream.Type = adTypeText
strTmp = objStream.ReadText
' close up and return
objStream.Close
ConvertUtf8BytesToString = strTmp
End Function
|