java util - Unicode转换工具

 

测试代码

package cn.java.codec.unicode;

public class Test {

    public static void main(String[] args) throws Exception {
        String str = "test中文";
        String unicodeEncode = UnicodeUtil.encode(str);
        System.out.println("UnicodeUtil.encode Result : " + unicodeEncode);
        
        str = UnicodeUtil.decode(unicodeEncode);
        System.out.println("UnicodeUtil.decode Result : " + str);
    }
}

输出内容

UnicodeUtil.encode Result : \u0074\u0065\u0073\u0074\u4e2d\u6587
UnicodeUtil.decode Result : test中文

 

 

工具类

package cn.java.codec.unicode;

/**
 * 每六位描述一个字节
 * @author zhouzhian
 */
public class UnicodeUtil {
    
    /**
     * 字符串编码成Unicode编码
     */
    public static String encode(String src) throws Exception {
        char c;
        StringBuilder str = new StringBuilder();
        int intAsc;
        String strHex;
        for (int i = 0; i < src.length(); i++) {
            c = src.charAt(i);
            intAsc = (int) c;
            strHex = Integer.toHexString(intAsc);
            if (intAsc > 128)
                str.append("\\u" + strHex);
            else
                str.append("\\u00" + strHex); // 低位在前面补00
        }
        return str.toString();
    }
    
    /**
     * Unicode解码成字符串
     * @param src
     * @return
     */
    public static String decode(String src) {
        int t =  src.length() / 6;
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < t; i++) {
            String s = src.substring(i * 6, (i + 1) * 6); // 每6位描述一个字节
            // 高位需要补上00再转
            String s1 = s.substring(2, 4) + "00";
            // 低位直接转
            String s2 = s.substring(4);
            // 将16进制的string转为int
            int n = Integer.valueOf(s1, 16) + Integer.valueOf(s2, 16);
            // 将int转换为字符
            char[] chars = Character.toChars(n);
            str.append(new String(chars));
        }
        return str.toString();
    }
}

 

转载于:https://www.cnblogs.com/xiaoyaogege/p/6306589.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值