java汉字转unicode编码
时间: 2023-09-06 18:13:53 浏览: 52
可以使用Java内置的Character类中的静态方法来将汉字转成Unicode编码,示例代码如下:
```
public static String chineseToUnicode(String str) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c >= 0 && c <= 127) {
result.append(c);
} else {
result.append("\\u").append(Integer.toHexString(c));
}
}
return result.toString();
}
```
使用方式:
```
String str = "你好";
String unicode = chineseToUnicode(str);
System.out.println(unicode);
```
输出结果:
```
\u4f60\u597d
```
其中,`\u`表示后面跟随的是16进制的Unicode编码值。所以,`\u4f60`就是汉字“你”的Unicode编码值,`\u597d`就是汉字“好”的Unicode编码值。
相关问题
java汉字转unicode编码并输出为short数组
可以在汉字转Unicode编码的基础上,再将每个Unicode编码值转成short类型,最后将所有short值存储到short数组中。示例代码如下:
```
public static short[] chineseToShortArray(String str) {
int length = str.length();
short[] result = new short[length];
for (int i = 0; i < length; i++) {
char c = str.charAt(i);
if (c >= 0 && c <= 127) {
result[i] = (short) c;
} else {
result[i] = (short) Integer.parseInt(Integer.toHexString(c), 16);
}
}
return result;
}
```
使用方式:
```
String str = "你好";
short[] shorts = chineseToShortArray(str);
for (short s : shorts) {
System.out.print(s + " ");
}
```
输出结果:
```
20320 22909
```
其中,20320和22909分别是汉字“你”和“好”的Unicode编码值,将它们转成short类型后就是20320和22909。
java unicode编码转换中文
Java 中可以使用 String 类中的 getBytes() 方法将 Unicode 编码转换为中文,例如:
```
String str = "中文";
byte[] bytes = str.getBytes("Unicode");
```
也可以使用 new String(bytes, "Unicode") 构造函数将 bytes 数组转换为字符串。
```
String str2 = new String(bytes, "Unicode");
```
这样就可以将unicode编码转换成中文了。