vbs中將GB2312轉(zhuǎn)Unicode的代碼

字號(hào):


    現(xiàn)在都是utf-8編碼的時(shí)代了。responseText對(duì)utf-8編碼支持得很好,但是如果是gb2312編碼就會(huì)返回亂碼,有時(shí)甚至?xí)?bào)錯(cuò)。
    今天寫了一個(gè)類似于下面的程序:
    代碼如下:
    Dim http
    Set http = CreateObject("msxml2.xmlhttp")
    http.open "GET","http://www.sina.com.cn/",False
    http.send
    WScript.Echo http.responseText
    但是卻發(fā)現(xiàn)返回的中文都是亂碼,看了一下發(fā)現(xiàn)新浪的編碼竟然是gb2312的,汗,現(xiàn)在都是utf-8編碼的時(shí)代了。responseText對(duì)utf-8編碼支持得很好,但是如果是gb2312編碼就會(huì)返回亂碼,有時(shí)甚至?xí)?bào)錯(cuò)。無奈,只好用responseBody然后自己轉(zhuǎn)碼。
    代碼如下:
    Dim http
    Set http = CreateObject("msxml2.xmlhttp")
    http.open "GET","http://www.sina.com.cn/",False
    http.send
    WScript.Echo GB2312ToUnicode(http.responseBody)
    于是就要自己寫一個(gè)GB2312ToUnicode函數(shù),用ado很容易實(shí)現(xiàn):
    代碼如下:
    Function GB2312ToUnicode(str)
    With CreateObject("adodb.stream")
    .Type = 1 : .Open
    .Write str : .Position = 0
    .Type = 2 : .Charset = "gb2312"
    GB2312ToUnicode = .ReadText : .Close
    End With
    End Function
    這樣返回的就是VBS字符串默認(rèn)的Unicode編碼了,不過用ado不能顯示我鬼使神差的VBS水平,于是自己根據(jù)“算法”再寫了一個(gè):
    代碼如下:
    Function GB2312ToUnicode(str)
    length = LenB(str) : out = ""
    For i = 1 To length
    c = AscB(MidB(str,i,1))
    If c <= 127 Then
    out = out & Chr(c)
    Else
    i = i + 1
    d = Hex(AscB(MidB(str,i,1)))
    c = "&H" & Hex(c) & d
    out = out & Chr(c)
    End If
    Next
    GB2312ToUnicode = out
    End Function
    只可惜效率太低,就當(dāng)練練手吧。