---
title: "一个将BIG5编码转换为GB2312编码的类"
author: "Eastsun"
date: "2007-02-25T17:28:39Z"
tags: []
slug: "big5-gb2312"
draft: false
lastmod: "2007-02-25T17:28:39Z"
id: 55607
url: "https://eastsun.iteye.com/blog/55607"
---

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

java 代码

01. import  java.io.\*;
02. /\**
03. \*实现由BIG5编码到GB2312编码转换的工具类
04. \*@author: Eastsun
05. \*@version: 2007.2.24 v0.5
06. \*/
07. public   class  Big2Gb{
08. private   static   final  String tabFile = "bg-gb.tab" ;
09. 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&gt;&gt;&gt; 8 )& 0xff ;
27. int  low  =big& 0xff ;
28. high -=  0xa1 ;
29. if (low&lt;= 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&lt;bs.length){
42. int  high =bs\[index]& 0xff ;
43. if (high&gt;= 0xa1 &&high&lt;= 0xfe ){
44. index ++;
45. if (index&gt;=bs.length)  break ;
46. int  low =bs\[index]& 0xff ;
47. if (low&lt; 0x40 ||low&gt; 0xfe )  continue ;
48. if (low&gt; 0x7e &&low&lt; 0xa1 )  continue ;
49. int  offset =indexOf((high&lt;&lt; 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. }