Java按不同的编码类型将十六进制数转化为String字符串代码
时间: 2023-04-09 22:03:08 浏览: 98
可以回答这个问题。Java中可以使用以下代码将十六进制数转化为String字符串:
String hexString = "48656c6c6f20576f726c64"; // 十六进制数
byte[] bytes = new byte[hexString.length() / 2];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) Integer.parseInt(hexString.substring(2 * i, 2 * i + 2), 16);
}
String str = new String(bytes, StandardCharsets.UTF_8);
System.out.println(str); // 输出 "Hello World"
相关问题
android 16进制转汉字,文本编码转换器(文本-十六进制 相互转换)
以下是Android中实现文本和十六进制相互转换的代码示例:
```java
public class HexUtils {
/**
* 将文本转换为十六进制字符串
* @param text 文本
* @return 十六进制字符串
*/
public static String textToHex(String text) {
byte[] bytes = text.getBytes();
StringBuilder hex = new StringBuilder();
for (byte b : bytes) {
hex.append(String.format("%02X", b));
}
return hex.toString();
}
/**
* 将十六进制字符串转换为文本
* @param hex 十六进制字符串
* @return 文本
*/
public static String hexToText(String hex) {
StringBuilder text = new StringBuilder();
for (int i = 0; i < hex.length(); i += 2) {
String hexByte = hex.substring(i, i + 2);
byte b = (byte) Integer.parseInt(hexByte, 16);
text.append((char) b);
}
return text.toString();
}
}
```
使用示例:
```java
String text = "Hello, world!";
String hex = HexUtils.textToHex(text);
Log.d("HexUtils", "textToHex: " + hex); // 输出: 48656C6C6F2C20776F726C6421
String text2 = HexUtils.hexToText(hex);
Log.d("HexUtils", "hexToText: " + text2); // 输出: Hello, world!
```
可以将以上代码封装成一个工具类,方便在项目中使用。
java解析字符串中的unicode编码转换成字符
在Java中,可以使用 Unicode 转义序列将 Unicode 编码表示为字符。Unicode 转义序列是由反斜杠和小写字母 u 组成的六位十六进制数,例如 "\u0041" 表示字符 'A'。
如果你的字符串中包含 Unicode 编码的字符,你可以使用 Java 内置的方法 `StringEscapeUtils.unescapeJava()` 进行转换。具体的实现步骤如下:
1. 导入 `org.apache.commons.lang3.StringEscapeUtils` 类。
2. 调用 `StringEscapeUtils.unescapeJava()` 方法,将字符串中的 Unicode 编码转换成对应的字符。
示例代码如下:
```java
import org.apache.commons.lang3.StringEscapeUtils;
public class UnicodeConverter {
public static void main(String[] args) {
String str = "\\u4e2d\\u6587";
String unescapedStr = StringEscapeUtils.unescapeJava(str);
System.out.println(unescapedStr); // 输出 "中文"
}
}
```
在上面的代码中,`StringEscapeUtils.unescapeJava()` 方法将字符串 "\\u4e2d\\u6587" 转换成了 "中文"。