VB6.0 如何将string 字符串转换成utf-8编码形式?

 我来答
匿名用户
推荐于2018-02-27
展开全部
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
匿名用户
2013-07-15
展开全部
这种转换一般用于网页地址; 我不知道 Delphi 是不是有现成的函数, 用到了就写了一个.

//函数:
function ToUTF8Encode(str: string): string;
var
b: Byte;
begin
for b in BytesOf(UTF8Encode(str)) do
Result := Format('%s%%%.2x', [Result, b]);
end;

//测试:
var
str: string;
begin
str := '万一';
str := ToUTF8Encode(str);
ShowMessage(str); //%E4%B8%87%E4%B8%80
end;

为 "小月124" 写了个反向函数:
function ToUTF8Decode(const str: string): string;
var
List: TStrings;
tmpStr: AnsiString;
i: Integer;
begin
List := TStringList.Create;
ExtractStrings(['%'], ['%'], PChar(str), List);
SetLength(tmpStr, List.Count);
for i := 0 to List.Count - 1 do
Byte(tmpStr[i+1]) := StrToInt('$' + List[i]);
List.Free;
Result := UTF8Decode(tmpStr);
end;

{ 调用测试 }
procedure TForm1.FormCreate(Sender: TObject);
var
s1: AnsiString;
s2: WideString;
begin
s1 := '%E4%B8%87%E4%B8%80';
s2 := ToUTF8Decode(s1);
ShowMessage(s2); { 万一 }
end;
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
匿名用户
2013-07-15
展开全部
这个问题太难啦不知道怎么回答
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
收起 1条折叠回答
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式