java 16进制byte数组 转为string
时间: 2023-11-21 19:04:50 浏览: 54
可以使用以下代码实现:
byte[] bytes = {0x48, 0x65, 0x6c, 0x6c, 0x6f}; //16进制byte数组
String str = new String(bytes, StandardCharsets.UTF_8); //转换为string
System.out.println(str); //输出 Hello
相关问题
android byte数组转16进制string
可以使用以下代码将 byte 数组转换为 16 进制字符串:
```java
public static String bytesToHex(byte[] bytes) {
StringBuilder hexString = new StringBuilder();
for (byte b : bytes) {
String hex = Integer.toHexString(0xFF & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
```
调用方法:
```java
byte[] byteArray = {0x01, 0x02, 0x03, (byte)0xFF};
String hexString = bytesToHex(byteArray);
System.out.println(hexString); // 输出:010203ff
```
注意:Java 中的 byte 类型是有符号的,范围为 -128 到 127。如果需要将 8 位二进制数表示的无符号数转为 byte 类型,可以使用 `int` 类型与 `0xFF` 进行按位与运算,如 `(byte)0xFF`。
java汉字转16进制并转为int数组
以下是Java中将汉字转换为16进制并转为int数组的代码示例:
```java
public static int[] hexStrToIntArray(String str) {
byte[] b = str.getBytes();
int[] result = new int[b.length];
for (int i = 0; i < b.length; i++) {
result[i] = Integer.parseInt(Integer.toHexString(b[i] & 0xff), 16);
}
return result;
}
```
这个方法首先将字符串转换为字节数组,然后将每个字节转换为16进制字符串,并使用 `Integer.parseInt()` 方法将其转换为整数类型,并将结果存储在 `int` 数组中返回。
使用示例:
```java
String str = "你好";
int[] result = hexStrToIntArray(str);
System.out.println(Arrays.toString(result)); // 输出[20320, 22909]
```
这个例子将 "你好" 转换为16进制表示,然后转换为整数数组。由于 "你" 的16进制表示为 "0xC4 0xE3",整数为 20320,"好" 的16进制表示为 "0xBA 0xC3",整数为 22909。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)