VB源码函数UTF8Encode UTF8编码,原内容中有URLENCODE内容的不作更改

时间:2023-01-10 11:56:08
VB源码函数UTF8Encode UTF8编码,原内容中有URLENCODE内容的不作更改

'┏〓〓〓〓〓〓〓〓〓 UTF8Encode_ForJs,start 〓〓〓〓〓〓〓〓〓┓
'[简介]:
'UTF8编码,原内容中有URLENCODE内容的不作更改
Function UTF8Encode_ForJs(ByVal szInput As String) As String
Dim wch As String
Dim uch As String
Dim szRet As String
Dim x As Long
Dim inputLen As Long
Dim nAsc As Long
Dim nAsc2 As Long
Dim nAsc3 As Long

If szInput = "" Then
UTF8Encode_ForJs = szInput
Exit Function
End If
inputLen = Len(szInput)
For x = 1 To inputLen
'得到每个字符
wch = Mid(szInput, x, 1)
'得到相应的UNICODE编码
nAsc = AscW(wch)
'对于<0的编码 其需要加上65536
If nAsc < 0 Then nAsc = nAsc + 65536
'对于<128位的ASCII的编码则无需更改
If (nAsc And &HFF80) = 0 Then
szRet = szRet & wch
Else
If (nAsc And &HF000) = 0 Then
'真正的第二层编码范围为000080 - 0007FF
'Unicode在范围D800-DFFF中不存在任何字符,基本多文种平面中约定了这个范围用于UTF-16扩展标识辅助平面(两个UTF-16表示一个辅助平面字符).
'当然,任何编码都是可以被转换到这个范围,但在unicode中他们并不代表任何合法的值。

uch = "%" & Hex(((nAsc \ 2 ^ 6)) Or &HC0) & Hex(nAsc And &H3F Or &H80)
szRet = szRet & uch




Else
'第三层编码00000800 – 0000FFFF
'首先取其前四位与11100000进行或去处得到UTF-8编码的前8位
'其次取其前10位与111111进行并运算,这样就能得到其前10中最后6位的真正的编码 再与10000000进行或运算来得到UTF-8编码中间的8位
'最后将其与111111进行并运算,这样就能得到其最后6位的真正的编码 再与10000000进行或运算来得到UTF-8编码最后8位编码
uch = "%" & Hex((nAsc \ 2 ^ 12) Or &HE0) & "%" & _
Hex((nAsc \ 2 ^ 6) And &H3F Or &H80) & "%" & _
Hex(nAsc And &H3F Or &H80)
szRet = szRet & uch
End If
End If
Next

UTF8Encode_ForJs = szRet
End Function
'┗〓〓〓〓〓〓〓〓〓 UTF8Encode_ForJs,end 〓〓〓〓〓〓〓〓〓┛