ITeye博客

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

Eastsun · 2007-02-25 17:28 · 编程技术 · Markdown

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. *取得BIG5汉字big在data中的偏移
  24. */
  25. private   static   int  indexOf( int  big){
  26. int  high =(big>>> 8 )& 0xff ;
  27. int  low  =big& 0xff ;
  28. high -=  0xa1 ;
  29. if (low<= 0x7e ) low -=  0x40 ;
  30. else           low -= ( 0xa1  - 0x7e  - 1 ) + 0x40 ;
  31. return   2 *(high* 157 +low);
  32. }
  33. /**
  34. *将保存在bs数字中的big5编码的字符串数据转换成gb2312编码的数据
  35. *注意:此方法将更改原先存储的数据
  36. *@param bs 需要转换的以big5编码的字符串数据
  37. *@return bs 经过转换的数据,保存在参数中的byte数组中
  38. */
  39. public   static   byte [] translateBig5ToGb( byte [] bs){
  40. int  index = 0 ;
  41. while (index<bs.length){
  42. int  high =bs[index]& 0xff ;
  43. if (high>= 0xa1 &&high<= 0xfe ){
  44. index ++;
  45. if (index>=bs.length)  break ;
  46. int  low =bs[index]& 0xff ;
  47. if (low< 0x40 ||low> 0xfe )  continue ;
  48. if (low> 0x7e &&low< 0xa1 )  continue ;
  49. int  offset =indexOf((high<< 8 )|low);
  50. bs[index- 1 ] =data[offset];
  51. bs[index  ] =data[offset+ 1 ];
  52. index++;
  53. }
  54. else  index++;
  55. }
  56. return  bs;
  57. }
  58. public   static  String translateBig5ToGb(String big){
  59. String result = null ;
  60. try {
  61. byte [] bs =big.getBytes( "big5" );
  62. bs =translateBig5ToGb(bs);
  63. result = new  String(bs, "gb2312" );
  64. } catch (Exception e){
  65. }
  66. return  result;
  67. }
  68. }

评论(3)

  1. #3 楼 · zhangts8888 · 2008-09-04 12:03

    :D 谢谢了。呵呵

  2. #2 楼 · wildwind · 2008-06-03 09:48

    Thanks

  3. #1 楼 · wufan0023 · 2008-04-07 09:58

    谢谢了,先拷贝下去看看能不能用。

评论功能维护中,当前仅展示历史评论。