今天做個小功能的時候遇到的問題,我當前的頁面是utf-8編碼,獲取百度來源url中的漢字編碼有可能是gb下的,在網上搜了很久,解決方法最多的一個例子是利用xmlhttp遠程請求一下再次獲取,但這樣無疑加重了代碼的執行效率,其他更好的方法也沒搜到,但這個方法肯定不能立即使用的,所以最終想到了另個辦法。
舉個例子,如:“漢字”
在utf-8下的編碼為:%E6%B1%89%E5%AD%97
在gb2312下的編碼為:%BA%BA%D7%D6
而我的網頁當前為utf-8編碼下,那麼如何將這些純粹的編碼字符串轉換為漢字呢?
首先,我的頁面中要包含下面這個函數:
Function URLDecode(enStr)
Dim deStr,strSpecial
Dim c,i,v
deStr=
strSpecial=!#$%&'()*+,.-_/:;<=>[email protected][/]^`{|}~%
For i=1 To Len(enStr)
c=Mid(enStr,i,1)
If c=% Then
v=eval(&h+Mid(enStr,i+1,2))
If inStr(strSpecial,Chr(v))>0 Then
deStr=deStr&Chr(v)
i=i+2
Else
v=eval(&h+ Mid(enStr,i+1,2) + Mid(enStr,i+4,2))
deStr=deStr & Chr(v)
i=i+5
End If
Else
If c=+ Then
deStr=deStr&
Else
deStr=deStr&c
End If
End If
Next
URLDecode=deStr
End Function
上面這個函數是一個url解碼函數,下面的函數是utf-8編碼轉換為漢字的函數:
Function UTF2GB(utfStr)
For Dig=1 To Len(utfStr)
'如果UTF8編碼文字以%開頭則進行轉換
If mid(UTFStr,Dig,1)=% Then
'UTF8編碼文字大於8則轉換為漢字
If Len(UTFStr) >= Dig+8 Then
GBStr=GBStr & ConvChinese(mid(UTFStr,Dig,9))
Dig=Dig+8
Else
GBStr=GBStr & mid(UTFStr,Dig,1)
End If
Else
GBStr=GBStr & mid(UTFStr,Dig,1)
End If
Next
UTF2GB = GBStr
End Function
'UTF8編碼文字將轉換為漢字
Function ConvChinese(x)
A=split(mid(x,2),%)
i=0
j=0
For i=0 To UBound(A)
A(i)=c16to2(A(i))
Next
For i=0 To UBound(A)-1
DigS=InStr(A(i),0)
Unicode=
For j=1 To DigS-1
If j=1 Then
A(i)=Right(A(i),Len(A(i))-DigS)
Unicode=Unicode & A(i)
Else
i=i+1
A(i)=Right(A(i),Len(A(i))-2)
Unicode=Unicode & A(i)
End If
Next
If Len(c2to16(Unicode))=4 Then
ConvChinese=ConvChinese & Chrw(Int(&H & c2to16(Unicode)))
Else
ConvChinese=ConvChinese & Chr(Int(&H & c2to16(Unicode)))
End If
Next
End Function
'二進制代碼轉換為十六進制代碼
Function c2to16(x)
i=1
For i=1 To len(x) Step 4
c2to16=c2to16 & Hex(c2to10(Mid(x,i,4)))
Next
End Function
'二進制代碼轉換為十進制代碼
Function c2to10(x)
c2to10=0
If x=0 Then Exit Function
i=0
For i= 0 To Len(x) -1
If Mid(x,Len(x)-i,1)=1 Then c2to10=c2to10+2^(i)
Next
End Function
'十六進制代碼轉換為二進制代碼
Function c16to2(x)
i=0
For i=1 To Len(Trim(x))
tempstr= c10to2(CInt(Int(&h & Mid(x,i,1))))
Do While Len(tempstr)<4
tempstr=0 & tempstr
Loop
c16to2=c16to2 & tempstr
Next
End Function
'十進制代碼轉換為二進制代碼
Function c10to2(x)
mysign=Sgn(x)
x=abs(x)
DigS=1
Do
If x<2^DigS Then
Exit Do
Else
DigS=DigS+1
End If
Loop
tempnum=x
i=0
For i=DigS To 1 Step-1
If tempnum>=2^(i-1) Then
tempnum=tempnum-2^(i-1)
c10to2=c10to2 & 1
Else
c10to2=c10to2 & 0
End If
Next
If mysign=-1 Then c10to2=- & c10to2
End Function
在正常的utf-8頁面下,我們可以直接這樣用:
Response.Write UTF2GB(%E6%B1%89%E5%AD%97)
即:UTF2GB(%E6%B1%89%E5%AD%97) = 漢字
但若當前utf8頁面獲取到的是一個gb下的編碼(如%BA%BA%D7%D6),該怎麼轉換成漢字呢?這時候就要用到上面那個URLDecode(enStr)解碼函數了,但不能直接用,要特別注意進行臨時改變下當前頁面的編碼模式,應用示例如下:
<%
Session.CodePage = 936 '強制轉換到GB2312下
Dim mykey:mykey = URLDecode(%BA%BA%D7%D6) 'GB下的編碼字符串
Session.CodePage = 65001 '將頁面再次回到utf-8編碼下
Response.write(mykey)
%>
這時就獲得了漢字了。怎麼樣,簡單吧,下次記得關注本站哦-在遠方。