public class BytesUtil { public static char[] hex = "0123456789ABCDEF".toCharArray(); public String bytesToHexStr(byte... bytes) { char[] result = new char[bytes.length * 2]; for (int i = 0; i < bytes.length; i++) { result[i] = hex[(bytes[i] >> 4) & 0x0F]; result[i + 1] = hex[bytes[i] & 0x0F]; } return new String(result); } public byte[] hexStrToBytes(String byteStr) { if (byteStr == null) { return null; } if (byteStr.length() % 2 != 0) { throw new RuntimeException("byteStr长度不是偶数,没法转"); } int resultLen = byteStr.length() / 2; byte[] result = new byte[resultLen]; char h, l; byte b; byteStr = byteStr.toUpperCase(); for (int i = 0; i < resultLen; i++) { h = byteStr.charAt(i); if ('0' <= h && h <= '9') { b = (byte) (0x0F0 & (h - '0')); } else if ('A' <= h && h <= 'F') { b = (byte) (0x0F0 & (h - 'A' + 10)); } else { throw new RuntimeException("byteStr 的第" + i + "个字符 不在16进制范围中"); } l = byteStr.charAt(i + 1); if ('0' <= l && l <= '9') { b |= (byte) (0x0F & (l - '0')); } else if ('A' <= l && l <= 'F') { b |= (byte) (0x0F & (l - 'A' + 10)); } else { throw new RuntimeException("byteStr 的第" + (i + 1) + "个字符 不在16进制范围中"); } result[i] = b; } return result; } }
字节工具
最新推荐文章于 2024-04-10 00:12:15 发布