将utf-8转换为unicode

时间:2021-07-07 23:26:54

将utf-8转换为unicode

'Utf8 转换为 Unicode
Public Function UTF8_Decode(ByVal s As String) As String   

   Dim lUtf8Size        As Long
   Dim sBuffer          As String
   Dim lBufferSize      As Long
   Dim lResult          As Long
   Dim b()              As Byte

   If LenB(s) Then
      On Error GoTo EndFunction
      b = StrConv(s, vbFromUnicode)
      lUtf8Size = UBound(b) + 1
      On Error GoTo 0
      'Set buffer for longest possible string i.e. each byte is
      'ANSI<=&HFF, thus 1 unicode(2 bytes)for every utf-8 character.
      lBufferSize = lUtf8Size * 2
      sBuffer = String$(lBufferSize, vbNullChar)
      'Translate using code page 65001(UTF-8)
      lResult = MultiByteToWideChar(CP_UTF8, 0, b(0), _
         lUtf8Size, StrPtr(sBuffer), lBufferSize)
      'Trim result to actual length
      If lResult Then
         UTF8_Decode = Left$(sBuffer, lResult)
         'Debug.Print UTF8_Decode
      End If
   End If

EndFunction:

End Function

 


'Unicode转换为UTF-8.
Public Function UTF8_Encode(ByVal strUnicode As String) As String   'ByVal strUnicode As Byte
   Dim TLen             As Long

   TLen = Len(strUnicode)
   If TLen = 0 Then Exit Function

   Dim lBufferSize      As Long
   Dim lResult          As Long
   Dim b()              As Byte
   'Set buffer for longest possible string.
   lBufferSize = TLen * 3 + 1
   ReDim b(lBufferSize - 1)
   'Translate using code page 65001(UTF-8).
   lResult = WideCharToMultiByte(CP_UTF8, 0, StrPtr(strUnicode), _
      TLen, b(0), lBufferSize, vbNullString, 0)
   'Trim result to actual length.
   If lResult Then
      lResult = lResult - 1
      ReDim Preserve b(lResult)
      UTF8_Encode = StrConv(b, vbUnicode)
   End If

End Function