GBK碼位分配及順序
GBK 亦采用雙字節表示,總體編碼范圍為 8140-FEFE,首字節在 81-FE 之間,尾字節在 40-FE 之間,剔除 xx7F 一條線。總計 23940 個碼位,共收入 21886 個漢字和圖形符號,其中漢字(包括部首和構件)21003 個,圖形符號 883 個。
生成的取模字庫,是從0開始,對應內碼0x8140.關鍵是還不是按順序排列,所以要計算偏移量。如果怕麻煩,直接使用unicode 偏移量0對應的就是unicode編碼0
1.直接計算 java版
優化版2.0
import java.io.UnsupportedEncodingException;
public class GBK {
/**
* @see 非標准 xx7f 這個他用?來代替,不用減了。
* @author 小黃人軟件
* @param code為漢字GBK編碼
* @return 返回偏移量
*/
public static int getGBKIndex2(int code)
{
//分為三塊來減
//1. 減0x8140前的所有
//2. 減xx00-xx3F 0xxxff 共0x41個字節
//3. xx7f 這個他用?來代替,不用減了。
int temp=code - 0x8140- (code/256-0x81)*0x41 ;
// if(code%256>0x7f)
// temp=temp-1;
return temp;
}
/**
* @see 標准
* @author 小黃人軟件
* @param code為漢字GBK編碼
* @return 返回偏移量
*/
public static int getGBKIndex(int code)
{
//分為三塊來減
//1. 減0x8140前的所有
//2. 減xx00-xx3F xx7f xxff 共0x42個
//3. 低字節做判斷 大於00x7f 減本次的1個xx7f
int temp=code - 0x8140- (code/256-0x81)*0x42 ;
if(code%256>0x7f)
temp=temp-1;
return temp;
}
public static void gbk(char c)
{
//吞 gbk:CDCC 定位14579
try {
//String gbk = new String("吞".getBytes("GBK"));
String gbk = new String(String.valueOf(c).getBytes("GBK")); //
//String gbk = new String("丂".getBytes("GBK"));
byte[] b=gbk.getBytes();
int gbkcode=(int)(256*(b[0]&0xff))+ (int) (b[1]&0xff );
int result=getGBKIndex(gbkcode);
System.out.println(String.format(gbk+" GBK:0x%04X 定位:%d \r\n",gbkcode, result));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str="丂亐0服非";
for(int i=0;i
{
gbk(str.charAt(i));
}
}
}
輸出:
丂 GBK:0x8140 定位:0
亐 GBK:0x8180 定位:63
0 GBK:0xA3B0 定位:6571
服 GBK:0xB7FE 定位:10449
非 GBK:0xB7C7 定位:10394
GBK:0xFE9F 定位:23844
老版1.0
import java.io.UnsupportedEncodingException;
public class GBK {
public static int getGBKIndex(int code) //返回偏移量 code為漢字GBK編碼
{
//分為三塊來減
//1. 減0x8140前的所有
//2. 減xx00-xx3F 0xxxff 共0x41個字節
//3. xx7f 做判斷 低字節 少於00x7f 只減之前的 大於則 減之前的+本次的1個字節
int temp=code - 0x8140- (code/256-0x81)*0x41 ;
if(code%256<0x7f)
temp=temp-(code/256-0x81);
else
temp=temp-(code/256-0x81)-1;
return temp;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//吞 定位14579 gbk:CDCC
try {
//String gbk = new String("吞".getBytes("GBK"));
String gbk = new String("丟".getBytes("GBK"));
//String gbk = new String("丂".getBytes("GBK"));
System.out.println(gbk);
byte[] b=gbk.getBytes();
System.out.println(String.format("0x%04X ", (int)(256*(b[0]&0xff))+ (int) (b[1]&0xff )));
int result=getGBKIndex((int)(256*(b[0]&0xff))+ (int) (b[1]&0xff ));
System.out.println(String.format("%02d ", result));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2.需要
100kb左右
unsigned int gbk[]={GBK所有字 比如: 丂,丄,丅,丆,丏,丒,丗,丟,丠,両,丣,並,丩,丮,丯,丱} ; //把所有字放入數組中
unsigned int getIndex(unsigned int c)
for(int i=0;i
{
if(gbk[i]==c)
return i;
}
}