当前位置 博文首页 > vbs中将GB2312转Unicode的代码

    vbs中将GB2312转Unicode的代码

    作者:admin 时间:2021-02-13 15:02

    今天写了一个类似于下面的程序:
    复制代码 代码如下:

    Dim http
    Set http = CreateObject("msxml2.xmlhttp")
    http.open "GET","http://www.sina.com.cn/",False
    http.send
    WScript.Echo http.responseText

    但是却发现返回的中文都是乱码,看了一下发现新浪的编码竟然是gb2312的,汗,现在都是utf-8编码的时代了。responseText对utf-8编码支持得很好,但是如果是gb2312编码就会返回乱码,有时甚至会报错。无奈,只好用responseBody然后自己转码。
    复制代码 代码如下:

    Dim http
    Set http = CreateObject("msxml2.xmlhttp")
    http.open "GET","http://www.sina.com.cn/",False
    http.send
    WScript.Echo GB2312ToUnicode(http.responseBody)

    于是就要自己写一个GB2312ToUnicode函数,用ado很容易实现:
    复制代码 代码如下:

    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字符串默认的Unicode编码了,不过用ado不能显示我鬼使神差的VBS水平,于是自己根据“算法”再写了一个:
    复制代码 代码如下:

    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

    只可惜效率太低,就当练练手吧。
    原文:http://demon.tw/programming/vbs-gb2312-unicode.html
    js
下一篇:没有了