java实现将16进制的字符串转成字节数组
时间: 2023-07-07 16:34:05 浏览: 58
可以使用 Java 内置的方法 `decode` 将 16 进制字符串转换为字节数组。以下是示例代码:
```java
public static byte[] hexStringToByteArray(String hexString) {
int length = hexString.length();
byte[] byteArray = new byte[length / 2];
for (int i = 0; i < length; i += 2) {
byteArray[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
+ Character.digit(hexString.charAt(i + 1), 16));
}
return byteArray;
}
```
使用示例:
```java
String hexString = "48656c6c6f20576f726c64"; // "Hello World" 的 16 进制表示
byte[] byteArray = hexStringToByteArray(hexString);
System.out.println(Arrays.toString(byteArray)); // 输出: [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
```
相关问题
Java 16进制字符串转字节数组代码
可以使用 `java.lang.String` 类中的 `getBytes()` 方法,将 16 进制字符串转为字节数组。以下是示例代码:
```java
public static byte[] hexStringToByteArray(String hexString) {
int len = hexString.length();
byte[] byteArray = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
byteArray[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
+ Character.digit(hexString.charAt(i+1), 16));
}
return byteArray;
}
```
这里的 `hexString` 是 16 进制字符串,返回的是对应的字节数组。
16进制字节数组转字符串数组
可以使用以下代码将一个16进制字节数组转换为字符串数组:
```java
public static String[] hexToStringArray(byte[] bytes) {
String[] result = new String[bytes.length / 2];
for (int i = 0; i < bytes.length; i += 2) {
result[i / 2] = new String(new char[]{(char) ((bytes[i] << 8) + (bytes[i + 1] & 0xff))});
}
return result;
}
```
这个方法首先创建一个字符串数组,其大小为输入字节数组的一半(因为每个字节对应一个16进制数,而每个16进制数对应一个字符)。然后,它循环遍历输入字节数组,每次处理两个连续的字节。对于每对字节,它将它们组合成一个char型的值,并使用这个值创建一个新的String对象。最后,它将所有的String对象存储在结果数组中并返回。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)