将utf-8转换为unicode

论坛 期权论坛 编程之家     
选择匿名的用户   2021-5-23 11:44   11   0

将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

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP