1.一个文字对应两个字节,“豫”占两个字节,GB2312编码为0xD4,0xA5,转为10进制就是212,165
//GB2321码转文字
public static String stringToGbk(String string) throws Exception
{
byte[] bytes = new byte[string.length() / 2];
for(int i = 0; i < bytes.length; i ++){
byte high = Byte.parseByte(string.substring(i * 2, i * 2 + 1), 16);
byte low = Byte.parseByte(string.substring(i * 2 + 1, i * 2 + 2), 16);
bytes[i] = (byte) (high << 4 | low);
}
String result = new String(bytes, "gbk");
return result;
}
2.十进制转十六进制
public static String toHex_array(int num) throws Exception {
char[] chs={'0','1','2','3','4',
'5','6','7','8','9',
'A','B','C','D','E',
'F'};//注意要从‘0’开始!!这样才能满足chs[1]='1'。
char[] arr=new char[8];
int i=arr.length;
while(num!=0){
int temp=num&15;
arr[--i]=chs[temp];
num=num>>>4;
}
String province = "";
for(int j=i;j<arr.length;j++)
province = province.concat(arr[j]+"");
return province;
}
测试代码,十进制数字212和165,先转化为十六进制,拼接转化为汉字
public static void main(String[] args) throws Exception {
String str = toHex_array(212) + toHex_array(165);
System.out.println("十进制数字转化为六进制后:"+str);
String result = stringToGbk(str);
System.out.println(result);
}