package net.geedge.util; public class HexUtils { /** * 16进制表示的字符串转换为字节数组 * * @param hexString 16进制表示的字符串 * @return byte[] 字节数组 */ public static byte[] hexStringToByteArray(String hexString) { hexString = hexString.replaceAll(" ", ""); int len = hexString.length(); byte[] bytes = new byte[len / 2]; for (int i = 0; i < len; i += 2) { // 两位一组,表示一个字节,把这样表示的16进制字符串,还原成一个字节 bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character .digit(hexString.charAt(i + 1), 16)); } return bytes; } /** * 字节转十六进制字符串 * @param b 需要进行转换的byte字节 * @return 转换后的Hex字符串 */ public static String byteToHex(byte b){ String hex = Integer.toHexString(b & 0xFF); if(hex.length() < 2){ hex = "0" + hex; } return hex; } /** * byte[]数组转换为16进制的字符串 * * @param bytes 要转换的字节数组 * @return 转换后的结果 */ public static String bytesToHexString(byte[] bytes) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(0xFF & bytes[i]); if (hex.length() == 1) { sb.append('0'); } sb.append(hex); } return sb.toString(); } /** * 合并字节数组:System.arraycopy()方法 * @param bt1 * @param bt2 * @return */ public static byte[] byteMerger(byte[] bt1, byte[] bt2){ byte[] bt3 = new byte[bt1.length+bt2.length]; System.arraycopy(bt1, 0, bt3, 0, bt1.length); System.arraycopy(bt2, 0, bt3, bt1.length, bt2.length); return bt3; } /** * 从一个byte[]数组中截取一部分 * @param src * @param begin * @param count * @return */ public static byte[] subBytes(byte[] src, int begin, int count) { byte[] bs = new byte[count]; for (int i=begin;i