java gbk转机内码_GBK/GB2312编码问题分析以及java获取汉字国标码
import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GBKEncodeUtil {
/**
* GB2312/GBK編碼類
*
* 機內碼,區位碼,國標碼 三者間存在聯系,由于機內碼,國標碼一般以四位十六進制的形式存在,區位碼以四位十進制表示。
*
* 舉例子:
* 德 ---區位碼:2134
* 機內碼: 高位字節 = 21(十進制) + A0H(十六進制) = 15H + A0H = B5H
* 低位字節 = 34(十進制) + A0H(十六進制) = 22H + A0H = C2H
* 機內碼: B5C2H
* 國標碼: 高位字節 = 21(十進制) + 20H(十六進制) = 15H + 20H = 35H
* 低位字節 = 34(十進制) + 20H(十六進制) = 22H + 20H = 42H
* 國標碼: 3542H
*
* 同理: 國標碼 = 機內碼 - 8080H
*/
public static void main(String[] args) {
String str = "德".trim();
System.out.println(str);
System.out.println("機內碼:0x" + getJineiMa(str));
System.out.println("區位碼:" + getLocationCode(str));
System.out.println("國標碼:0x" + getGBCode(str));
System.out.println(getCharacter("B0A1"));
}
/**
* 判斷str是否為漢字
* @param str 待檢測值
* @return true 是 false 不是
*/
public static boolean isCharacter(String str){
Pattern p_str = Pattern.compile("[\\u4e00-\\u9fa5]+");
Matcher m = p_str.matcher(str);
if(m.find()&&m.group(0).equals(str)){
return true;
}
return false;
}
/**
* 獲取機內碼
* @param chineseName
* @return 漢字的機內碼 String類型
*/
public static String getJineiMa(String chineseName){
StringBuffer sb = new StringBuffer();
try {
char[]ch = chineseName.toCharArray();
for (char c : ch){
if (isCharacter(String.valueOf(c))){
byte[]by = String.valueOf(c).getBytes("GBK");
for (byte b : by){
sb.append(Integer.toHexString(b & 0xff));
}
}else{
byte b = (byte) c;
sb.append(Integer.toHexString(b & 0xff));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString().toUpperCase().trim();
}
/**
* 獲得漢字區位碼
*
* @param chineseName 漢字
*
* @return 單個漢字區位碼
*/
public static String getLocationCode(String chineseName){
// 先判斷chinese是否為漢字
if (!isCharacter(chineseName)) return "輸入的不是漢字!";
String jiNeiMa = getJineiMa(chineseName);
String highOrder = jiNeiMa.substring(0, 2); // 高位
String lowOrder = jiNeiMa.substring(2, 4); // 低位
String quWeiMa = String.valueOf((Integer.parseInt(highOrder, 16) - 0xA0)) + String.valueOf(Integer.parseInt(lowOrder, 16) - 0xA0);
return quWeiMa;
}
/**
* 獲取 國標碼
* @param chineseName
* @return
*/
public static String getGBCode(String chineseName){
// 先判斷chinese是否為漢字
if (!isCharacter(chineseName)) return "輸入的不是漢字!";
int jiNeiMa = Integer.parseInt(getJineiMa(chineseName), 16);
String gbMa = Integer.toHexString(jiNeiMa - 0x8080);
return gbMa;
}
/**
根據機內碼獲取漢字
* @param quWeiMa
* @return 漢字
*/
public static String getCharacter(String jiNeiMa){
byte b1 = (byte) Integer.parseInt(jiNeiMa.substring(0, 2), 16);
byte b2 = (byte) Integer.parseInt(jiNeiMa.substring(2, 4), 16);
String str = null;
try {
str = new String(new byte[]{b1,b2}, "GBK");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return str;
}
}
總結
以上是生活随笔為你收集整理的java gbk转机内码_GBK/GB2312编码问题分析以及java获取汉字国标码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 无人机刚体运动学方程
- 下一篇: html5 indexeddb 排序,H