电脑爱好者,提供IT资讯信息及各类编程知识文章介绍,欢迎大家来本站学习电脑知识。 最近更新 | 联系我们 RSS订阅本站最新文章
电脑爱好者
站内搜索: 
当前位置:首页>> Vbscript>>asp中gb2312编码和utf-8编码互相转换的函数:

asp中gb2312编码和utf-8编码互相转换的函数

来源:网络 | 2014-11-5 | (有1955人读过)

和大家分享一个ASP里gb2312编码转换为uft-8编码的函数,非常有用的: <br />
<%
Function toUTF8(szInput) 
Dim wch, uch, szRet 
Dim x 
Dim nAsc, nAsc2, nAsc3 
'如果输入参数为空,则退出函数 
If szInput = "" Then 
toUTF8 = szInput 
Exit Function 
End If 
For x = 1 To Len(szInput) 
wch = Mid(szInput, x, 1)  
nAsc = AscW(wch) 
If nAsc < 0 Then nAsc = nAsc + 65536 

If (nAsc And &HFF80) = 0 Then 
szRet = szRet & wch 
Else 
If (nAsc And &HF000) = 0 Then 
uch = "%" & Hex(((nAsc \ 2 ^ 6)) Or &HC0) & Hex(nAsc And &H3F Or &H80) 
szRet = szRet & uch 
Else 
uch = "%" & Hex((nAsc \ 2 ^ 12) Or &HE0) & "%" & _ 
Hex((nAsc \ 2 ^ 6) And &H3F Or &H80) & "%" & _ 
Hex(nAsc And &H3F Or &H80) 
szRet = szRet & uch 
End If 
End If 
Next 
toUTF8 = szRet 
End Function 
function UTF2GB(UTFStr) 
dim dig,GBStr 
for Dig=1 to len(UTFStr) 
if mid(UTFStr,Dig,1)="%" then 
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 

function ConvChinese(x) 
dim A,i,j,DigS,Unicode 
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) 
dim i 
i=1 
for i=1 to len(x) step 4 
c2to16=c2to16 & hex(c2to10(mid(x,i,4))) 
next 
end function 

function c2to10(x) 
dim i 
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) 
dim i,tempstr 
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) 
dim mysign,DigS,tempnum,i 
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 
%>
来看一个这个转码函数的使用实例:
<%
dim str
str1=toutf8("电脑爱好者家园www.cncfan.com") 
str2=UTF2GB("%E7%94%B5%E8%84%91%E7%88%B1%E5%A5%BD%E8%80%85%E5%AE%B6%E5%9B%ADwww.cncfan.com")
Response.Write str1 & "<br />"
Response.Write str2
%>

Vbscript热门文章排行
网站赞助商
购买此位置

 

关于我们 | 网站地图 | 文档一览 | 友情链接| 联系我们

Copyright © 2003-2024 电脑爱好者 版权所有 备案号:鲁ICP备09059398号