tech.mhuang.pacebox.springboot.wechat.common.util.unicode.UnicodeUtil Maven / Gradle / Ivy
package tech.mhuang.pacebox.springboot.wechat.common.util.unicode;
import tech.mhuang.pacebox.core.exception.BusinessException;
import java.io.UnsupportedEncodingException;
/**
* unicode工具类
*
* @author mhuang
* @since 1.0.0
*/
public class UnicodeUtil {
/**
* 字符串转换unicode
*
* @param string str
* @return String
*/
public static String string2Unicode(String string) {
try {
StringBuilder out = new StringBuilder();
byte[] bytes = string.getBytes("unicode");
for (int i = 2; i < bytes.length - 1; i += 2) {
out.append("\\u");
String str = Integer.toHexString(bytes[i + 1] & 0xff);
out.append("0".repeat(2 - str.length()));
String str1 = Integer.toHexString(bytes[i] & 0xff);
out.append(str);
out.append(str1);
}
return out.toString().toUpperCase();
} catch (UnsupportedEncodingException e) {
throw new BusinessException(e);
}
}
/**
* unicode 转字符串
*
* @param unicode unicode
* @return String
*/
public static String unicode2String(String unicode) {
int n = unicode.length() / 6;
StringBuilder sb = new StringBuilder(n);
for (int i = 0, j = 2; i < n; i++, j += 6) {
String code = unicode.substring(j, j + 4);
char ch = (char) Integer.parseInt(code, 16);
sb.append(ch);
}
return sb.toString();
}
}