2007-02-25

一个将BIG5编码转换为GB2312编码的类

关键字: big5 gb2312 简体 繁体 转换

RT,就是利用BIG5与GB2312码的对照表,代码本身很容易,只是找对照表花了我很长时间.

java 代码
  1. import java.io.*;   
  2. /**  
  3. *实现由BIG5编码到GB2312编码转换的工具类  
  4. *@author: Eastsun  
  5. *@version: 2007.2.24 v0.5  
  6. */  
  7. public class Big2Gb{   
  8.     private static final String tabFile ="bg-gb.tab";   
  9.     private static byte[] data;   
  10.     static{   
  11.         try{   
  12.             FileInputStream fis =new FileInputStream(tabFile);   
  13.             int len =fis.available();   
  14.             data =new byte[len];   
  15.             fis.read(data);   
  16.             fis.close();   
  17.         }catch(Exception ex){   
  18.             ex.printStackTrace();   
  19.             System.exit(1);   
  20.         }   
  21.     }   
  22.        
  23.     /**  
  24.     *取得BIG5汉字big在data中的偏移  
  25.     */  
  26.     private static int indexOf(int big){   
  27.         int high =(big>>>8)&0xff;   
  28.         int low  =big&0xff;   
  29.            
  30.         high -= 0xa1;   
  31.         if(low<=0x7e) low -= 0x40;   
  32.         else          low -= (0xa1 -0x7e -1) +0x40;   
  33.            
  34.         return 2*(high*157+low);   
  35.     }   
  36.     /**  
  37.     *将保存在bs数字中的big5编码的字符串数据转换成gb2312编码的数据  
  38.     *注意:此方法将更改原先存储的数据  
  39.     *@param bs 需要转换的以big5编码的字符串数据  
  40.     *@return bs 经过转换的数据,保存在参数中的byte数组中  
  41.     */  
  42.     public static byte[] translateBig5ToGb(byte[] bs){   
  43.         int index =0;   
  44.         while(index<bs.length){   
  45.             int high =bs[index]&0xff;   
  46.             if(high>=0xa1&&high<=0xfe){   
  47.                 index ++;   
  48.                 if(index>=bs.length) break;   
  49.                 int low =bs[index]&0xff;   
  50.                 if(low<0x40||low>0xfecontinue;   
  51.                 if(low>0x7e&&low<0xa1continue;   
  52.                 int offset =indexOf((high<<8)|low);   
  53.                 bs[index-1] =data[offset];   
  54.                 bs[index  ] =data[offset+1];   
  55.                 index++;   
  56.             }   
  57.             else index++;   
  58.         }   
  59.         return bs;   
  60.     }   
  61.        
  62.     public static String translateBig5ToGb(String big){   
  63.         String result =null;   
  64.         try{   
  65.             byte[] bs =big.getBytes("big5");   
  66.             bs =translateBig5ToGb(bs);   
  67.             result =new String(bs,"gb2312");   
  68.         }catch(Exception e){   
  69.         }   
  70.         return result;   
  71.     }   
  72.        
  73. }  
  • bg2gb.rar (16.4 KB)
  • 描述: 源代码及对照表
  • 下载次数: 60
评论
zhangts8888 2008-09-04
谢谢了。呵呵
wildwind 2008-06-03
Thanks
wufan0023 2008-04-07
谢谢了,先拷贝下去看看能不能用。
发表评论

您还没有登录,请登录后发表评论

Eastsun
搜索本博客
我的相册
1b680e5a-efae-3ec3-8ccd-970a4a72a056-thumb
6.5beta.PNG
共 61 张
最近加入圈子
存档
最新评论