package org.yzh.commons.util;
|
|
import java.io.ByteArrayOutputStream;
|
import java.io.IOException;
|
import java.io.ObjectOutputStream;
|
|
/**
|
* 字节操作工具类
|
*/
|
public class BytesUtils {
|
|
/**
|
* 十六进制字符串转字节数组
|
*/
|
public static byte[] hex2bytes(String hex) {
|
if (hex == null || hex.isEmpty()) {
|
return new byte[0];
|
}
|
// 去除空格
|
hex = hex.replace(" ", "");
|
|
int len = hex.length();
|
if (len % 2 != 0) {
|
throw new IllegalArgumentException("十六进制字符串长度必须为偶数");
|
}
|
|
byte[] bytes = new byte[len / 2];
|
for (int i = 0; i < len; i += 2) {
|
bytes[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
|
+ Character.digit(hex.charAt(i + 1), 16));
|
}
|
return bytes;
|
}
|
|
/**
|
* 字节数组转十六进制字符串
|
*/
|
public static String bytes2hex(byte[] bytes) {
|
if (bytes == null || bytes.length == 0) {
|
return "";
|
}
|
StringBuilder result = new StringBuilder(bytes.length * 2);
|
for (byte b : bytes) {
|
result.append(String.format("%02X", b));
|
}
|
return result.toString();
|
}
|
|
public static byte[] convertToBytes(Object object) throws IOException {
|
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
ObjectOutputStream oos = new ObjectOutputStream(bos)) {
|
oos.writeObject(object);
|
return bos.toByteArray();
|
}
|
}
|
|
// 其他工具方法...
|
}
|