VB 문자와 UTF8 형식 상호 변환

2128 단어 VB
VB 모듈 파일에 다음 코드를 추가합니다.
Private Declare Function MultiByteToWideChar Lib "kernel32 " (ByVal CodePage As Long, ByVal dwFlags As Long, ByVal lpMultiByteStr As Long, ByVal cchMultiByte As Long, ByVal lpWideCharStr As Long, ByVal cchWideChar As Long) As Long
Private Declare Function WideCharToMultiByte Lib "kernel32 " (ByVal CodePage As Long, ByVal dwFlags As Long, ByVal lpWideCharStr As Long, ByVal cchWideChar As Long, ByVal lpMultiByteStr As Long, ByVal cchMultiByte As Long, ByVal lpDefaultChar As Long, ByVal lpUsedDefaultChar As Long) As Long
Private Const CP_ACP = 0 ' default to ANSI code page
Private Const CP_UTF8 = 65001 ' default to UTF-8 code page

'    UTF8
Public Function EncodeToBytes(ByVal sData As String) As Byte() ' Note: Len(sData) > 0
Dim aRetn() As Byte
Dim nSize As Long
nSize = WideCharToMultiByte(CP_UTF8, 0, StrPtr(sData), -1, 0, 0, 0, 0) - 1
If nSize = 0 Then Exit Function
ReDim aRetn(0 To nSize - 1) As Byte
WideCharToMultiByte CP_UTF8, 0, StrPtr(sData), -1, VarPtr(aRetn(0)), nSize, 0, 0
EncodeToBytes = aRetn
Erase aRetn
End Function

' UTF8    
Public Function DecodeToBytes(ByVal sData As String) As Byte() ' Note: Len(sData) > 0
Dim aRetn() As Byte
Dim nSize As Long
nSize = MultiByteToWideChar(CP_UTF8, 0, StrPtr(sData), -1, 0, 0) - 1
If nSize = 0 Then Exit Function
ReDim aRetn(0 To 2 * nSize - 1) As Byte
MultiByteToWideChar CP_UTF8, 0, StrPtr(sData), -1, VarPtr(aRetn(0)), nSize
DecodeToBytes = aRetn
Erase aRetn
End Function
Private Sub Command1_Click()
Dim s As String
s = StrConv(EncodeToBytes("  "), vbUnicode) ' utf      VB     
MsgBox s
t = DecodeToBytes(StrConv(s, vbFromUnicode))
MsgBox t
End Sub

'

사용 방법: 1, utf8 회전 VB 문자열
    Private Sub Utf8ToVBstr_Click()
        Dim vbstr As String
        vbstr  = DecodeToBytes(StrConv(       utf8   , vbFromUnicode))
        MsgBox vbstr 
    End Sub

2, VB 문자열 회전utf8
Private Sub VBstrToUtf8_Click()
    Dim utf8str As String
	utf8str =EncodeToBytes(       VB   );
    MsgBox utf8str 
End Sub

좋은 웹페이지 즐겨찾기