明晨网络

用户名: 密码:       注册 | 忘记密码 | 帮助中心 | 付款方式
7 × 24小时服务热线:400-672-9900

VB代码:将字符串转换为UTF-8编码方式的字节数组

2009-08-10 16:02,明晨网络原创,文章标签: UTF-8 编码 VB BASE64

    手头的工程需要使用SQLyogTunnel.php隧道对MYSQL数据库进行操作,为了保持最大程度的兼容,传输中始终使用BASE64对数据进行编码,数据库编码方式是utf-8。这样向该隧道发送数据时,就需要获取中文字符串的utf-8编码方式下的Base64编码。工程中,使用VB设计客户端程序与隧道通信,vb是微软旗下产品,使用unicode的编码方式。

    明晨网络mingchennet.com发布过vb下的base64编码的类,这个类还可以计算字节数组的base64编码,所以如果将中文字符串转换为UTF-8编码方式的字节数组,就可以达到目的了。

    做采集程序时,常常需要将UTF-8编码方式的网页内容转化为gb2312格式的字符串,实现这个功能的函数最有名的是BytesToBstr,使用了ADODB.Stream对象。借助ADODB.Stream,我们还可以将字符串转化为指定编码格式的字节数组。

 

  1. '======================================== 
  2. '函数名称:BytesToBstr 
  3. '函数作用:将二进制数据根据指定编码格式转换为字符串 
  4. '函数参数:内容,编码 
  5. '函数说明:明晨网络 MingchenNet.com 
  6. '======================================== 
  7. Public Function BytesToBstr(ByVal Body, ByVal Cset) As String 
  8.     On Error GoTo ErrHandle: 
  9.     Dim objStream As Object 
  10.     Dim sT As String 
  11.     Set objStream = CreateObject("ADODB.Stream"
  12.     objStream.Type = 1 
  13.     objStream.Mode = 3 
  14.     objStream.Open 
  15.     objStream.Write Body 
  16.     objStream.Position = 0 
  17.     objStream.Type = 2 
  18.     objStream.CharSet = Cset 
  19.     sT = objStream.ReadText 
  20.     objStream.Close 
  21.     Set objStream = Nothing 
  22.     BytesToBstr = sT 
  23.     Exit Function 
  24. ErrHandle: 
  25.     Set objStream = Nothing 
  26. End Function 
  27.  
  28.  
  29. '======================================== 
  30. '函数名称:Str2Byte 
  31. '函数作用:将字符串转化为指定编码格式的数组 
  32. '函数参数:内容,编码 
  33. '函数说明:明晨网络 MingchenNet.com 
  34. '======================================== 
  35. Public Function Str2Byte(ByVal Str As StringOptional ByVal CharSet As String = "utf-8"As Byte() 
  36. On Error GoTo ErrHandle: 
  37.     Dim objStream As Object 
  38.     Dim tByte() As Byte 
  39.     Set objStream = CreateObject("ADODB.Stream"
  40.     objStream.CharSet = CharSet 
  41.     objStream.Type = 2 
  42.     objStream.Mode = 3 
  43.     objStream.Open 
  44.     objStream.WriteText Str 
  45.     objStream.Flush 
  46.     objStream.Position = 0 
  47.     objStream.Type = 1 
  48.     objStream.Read 3 
  49.     tByte = objStream.Read() 
  50.     objStream.Close 
  51.     Set objStream = Nothing 
  52.     Str2Byte = tByte 
  53.     Exit Function 
  54. ErrHandle: 
  55.     Set objStream = Nothing 
  56. End Function 

文章源自:明晨网络,明晨网络原创,VB代码:将字符串转换为UTF-8编码方式的字节数组,http://www.mingchennet.com