常见的中文字符集有:GB2312字符集、GBK 字符集、BIG5字符集、 GB 18030字符集。其中GB2312字符集、GBK 字符集、BIG5字符集都是采用两个字节表示一个汉字。下面的程序中h表示字符的高字节位、l表示字符的低字节位,十六进制数值表示的是各种字符编码集的边界。
public static boolean isGB2312(byte h, byte l){
int ih = h & 0xff;
int il = l & 0xff;
return ((ih>=0xa1 && ih<=0xf7 &&
il>=0xa1 && il<=0xfe) ? true : false);
}
public static boolean isGBK(byte h, byte l){
int ih = h & 0xff;
int il = l & 0xff;
return ((ih>=0x81 && ih<=0xfe &&
(il>=0x40 && il<=0x7e ||
il>=0x80 && il<=0xfe )) ? true : false);
}
public static boolean isBIG5(byte h, byte l){
int ih = h & 0xff;
int il = l & 0xff;
return ((ih>=0xa1 && ih<=0xf9 &&
(il>=0x40 && il<=0x7e ||
il>=0xa1 && il<=0xfe )) ? true : false);
}
这个方法已经用到了Yard中文分词系统中进行字符集的判断,同时如果你读过mysql的源码你会发现mysql里对字符集的判断也是采用这种方法。