GB2312编码与区位码原理及ASP实现方法
经过对编码机制的研究,理清了GB2312编码与区位码之间的内在联系,据此编写了该程序。
经搜索发现,网上鲜有此类实现,故在此分享。
原创首发:
http://bbs.blueidea.com
http://mytju.com/classcode/
允许任意转载和使用。
1.简述
(1)GB2312标准的本质即为区位码体系。
该体系包含94行和94列,其中行对应区号,列对应位号。
例如汉字“啊”,其区号为16,位号为01,组合后的区位码即为1601。
(2)每个字符由区号和位号共同组成,占用两个字节。
这两个字节的数值范围均为01-94,这与通信控制符0-31存在冲突,
因此,需将区号和位号分别加上32,以避开冲突区域。
(3)经过上述处理后,每个字节范围变为33-126,这又与ASCII编码0-127产生重叠,
所以需将最高位置为1,即再加上128,从而彻底避免冲突。
最终,GB2312内码的每个字节取值范围为161-254。
2。实现
原理十分直观,仅需进行简单的加减运算即可完成转换。
现将已完成的函数代码直接列出。
'----取得区位码的函数---------------------
Function CharToQWM(byVal str)
dim sHex,sHigh,sLow,iLow,iHigh,sResult
sHex=Hex(Asc(str)) '获取字符的内码编码,如B0A1,此顺序正确,无需交换高低位。
sHigh=Left(sHex,2) '提取编码的高位部分,如B0。
sLow=Right(sHex,2) '提取编码的低位部分,如A1。
'GB2312内码范围为&HA1A1--&HFEFE,每个字节均位于A1-FE之间。
if NOT (sHigh>="A1" AND sHigh<="FE") then
CharToQWM=""
Exit Function
end if
if NOT (sLow>="A1" AND sLow<="FE") then
CharToQWM=""
Exit Function
end if
'GB交换码仅使用7位,高位置1即形成内码。反之,将高位置0即可还原为交换码。
iLow=Clng("&H" & sLow)-128
iHigh=Clng("&H" & sHigh)-128
'区位码与控制码0-31冲突,故加32后得到交换码。逆向操作即减去32。
iLow=iLow-32
iHigh=iHigh-32
'此时已成功获取区位码。
sResult=""
if iHigh<10 then
sResult = sResult & "0" & Cstr(iHigh)
else
sResult = sResult & Cstr(iHigh)
end if
if iLow<10 then
sResult = sResult & "0" & Cstr(iLow)
else
sResult = sResult & Cstr(iLow)
end if
CharToQWM=sResult
End Function
'----根据区位码得到字符的函数---------------------
Function QWMToChar(byVal str,byVal doCheckFlg)
dim sHex,sHigh,sLow,iLow,iHigh,sResult
'-------------检查输入格式--------------
if doCheckFlg then
if Len(str)<>4 then
QWMToChar=""
Exit Function
end if
'--4位必须都是数字
dim i,iAsc
for i=1 to 4
iAsc=Asc(mid(str,i,1))
if NOT (iAsc>=&H30 AND iAsc<=&H39) then
QWMToChar=""
Exit Function
end if
next
'--区号,位号都要在01-94之间
iHigh=Clng(Left(str,2))
iLow=Clng(Right(str,2))
if NOT (iHigh>=1 AND iHigh<=94) then
QWMToChar=""
Exit Function
end if
if NOT (iLow>=1 AND iLow<=94) then
QWMToChar=""
Exit Function
end if
end if
'-------------检查完毕------------------
iHigh=Clng(Left(str,2))
iLow=Clng(Right(str,2))
iHigh=iHigh + 32 + 128
iLow=iLow + 32 + 128
sHex=Hex(iHigh) & Hex(iLow)
QWMToChar=Chr("&H" & sHex)
End Function
使用方法:
-----------------------------------------------------------------------------------------------------
dim i,str,sChar
str="娃哈哈"
for i=1 to Len(str)
sChar=Mid(str,i,1)
Response.write sChar & ":" & CharToQWM(sChar) &"
"
next
-----------------------------------------------------------------------------------------------------
dim str
str="1601|1602|1603}]
if instr(str,"|")>0 then
dim s,sCharArray,i
sCharArray=Split(str,"|")
for i=0 to Ubound(sCharArray)
s=s & QWMToChar(trim(sCharArray(i)),True)
next
str=s
else
str=QWMToChar(str,True)
end if
.......
-----------------------------------------------------------------------------------------------------
3.在线使用
http://www.mytju.com/classcode/tools/quweima.asp
访问上述网址即可在线查询转换结果。