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<str.length();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<sizeof(gbk);i++)
{
if(gbk[i]==c)
return i;
}
}