java实现十六进制字符实现十六进制字符unicode与中英文转换示例与中英文转换示例
当需要对一个unicode十六进制字符串进行编码时,首先做的应该是确认字符集编码格式,在无法快速获知的情
况下,通过一下的str4all方法可以达到这一目的
关于unicode和utf的关系,可以简单的记忆:Unicode是一个编码组织、一个编码规范、在java中指utf-16;utf是Unicode编码
的translation转换格式,以便于很好地在网络中传递、在存储媒介汇总保存,于是utf存在多种格式,如8、16、32,而关联
le、te的区别,Unicode编码格式才会有以下过程中的10种。
复制代码 代码如下:
public static void main(String[] args) throws UnsupportedEncodingException {
StringUtil.str2all("0 产品型号描述");
StringUtil.str4all("30000900A74EC1548B57F753CF63F08F");
}
/**
* 尝试所有编码格式对十六进制数字字符串进行编码
*
* @param hexStr
* @throws UnsupportedEncodingException
*/
public static void str4all(String uStr) throws UnsupportedEncodingException{
System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++");
byte[] bs = new byte[uStr.length()/2];
for (int i = 0; i < bs.length; i++) {
bs[i] = (byte) Integer.parseInt(uStr.substring(i*2, i*2+2), 16);
}
System.out.println(new String(bs, "utf-8"));
// 16
System.out.println(new String(bs, "utf-16")); // 同unicode
System.out.println(new String(bs, "utf-16le"));
System.out.println(new String(bs, "x-utf-16le-bom"));
System.out.println(new String(bs, "utf-16be"));
// System.out.println(new String(bs, "x-utf-16be-bom")); // UnsupportedEncodingException
// 32
System.out.println(new String(bs, "utf-32"));
System.out.println(new String(bs, "utf-32le"));
System.out.println(new String(bs, "x-utf-32le-bom"));
System.out.println(new String(bs, "utf-32be"));
System.out.println(new String(bs, "x-utf-32le-bom"));
}
/**
* 列出所有编码对应的解码后的十六进制数字字符串
*
* @param uStr
* @throws UnsupportedEncodingException
*/
public static void str2all(String uStr) throws UnsupportedEncodingException{
System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++");
byte[] bs = new byte[]{};
bs = uStr.getBytes("utf-8");
for(byte b:bs){
System.out.print(Integer.toHexString(b & 0xff));
}
System.out.println();
// 16
bs = uStr.getBytes("utf-16");
for(byte b:bs){
System.out.print(Integer.toHexString(b & 0xff));
}
System.out.println();