zl程序教程

您现在的位置是:首页 >  其他

当前栏目

javabig5到gb2312的编码转换

转换编码 GB2312
2023-06-13 09:14:07 时间
packagecom.Big5ToUTF8;
importjava.io.*;
publicclassBig5Tran{
privatestaticfinalStringtabFile="bg-gb.tab";
privatestaticbyte[]data;
static{
try{
FileInputStreamfis=newFileInputStream(tabFile);
intlen=fis.available();
data=newbyte[len];
fis.read(data);
fis.close();
}catch(Exceptionex){
ex.printStackTrace();
System.exit(1);
}
}
/**
*取得BIG5汉字big在data中的偏移
*/
privatestaticintindexOf(intbig){
inthigh=(big>>>8)&0xff;
intlow=big&0xff;
high-=0xa1;
if(low<=0x7e)low-=0x40;
elselow-=(0xa1-0x7e-1)+0x40;
return2*(high*157+low);
}
/**
*将保存在bs数字中的big5编码的字符串数据转换成gb2312编码的数据
*注意:此方法将更改原先存储的数据
*@parambs需要转换的以big5编码的字符串数据
*@returnbs经过转换的数据,保存在参数中的byte数组中
*/
publicstaticbyte[]translateBig5ToGb(byte[]bs){
intindex=0;
while(index<bs.length){
inthigh=bs[index]&0xff;
if(high>=0xa1&&high<=0xfe){
index++;
if(index>=bs.length)break;
intlow=bs[index]&0xff;
if(low<0x40||low>0xfe)continue;
if(low>0x7e&&low<0xa1)continue;
intoffset=indexOf((high<<8)|low);
bs[index-1]=data[offset];
bs[index]=data[offset+1];
index++;
}
elseindex++;
}
returnbs;
}
publicstaticStringtranslateBig5ToGb(Stringbig){
Stringresult=null;
try{
byte[]bs=big.getBytes("big5");
bs=translateBig5ToGb(bs);
result=newString(bs,"gb2312");
}catch(Exceptione){
}
returnresult;
}
}