/* ---------------------------------------------------------- * 文件名称:ArrayUtils.java * * 作者:秦建辉 * * MSN:splashcn@msn.com * QQ:36748897 * * 博客:http://www.firstsolver.com/wordpress/ * * 开发环境: * Eclipse Juno * Java SE 7u5 * * 版本历史: * V1.0 2012年08月17日 * 字节数组与十六进制字符串之间的转换 ------------------------------------------------------------ */ package com.firstsolver.util; public class ArrayUtils { // 将字节数组转换成十六进制字符串 public static String ByteArray2HexString(byte[] input) { // 生成十六进制字符串 StringBuilder sb = new StringBuilder(input.length << 1); for(byte b : input) { sb.append(Integer.toHexString((b >> 4) & 0x0F)); // 高4位 sb.append(Integer.toHexString(b & 0x0F)); // 低4位 } return sb.toString().toUpperCase(); } // 将十六进制字符串转换成字节数组 public static byte[] HexString2ByteArray(String input) { int length = input.length(); if((length % 2) != 0) throw new IllegalArgumentException(); byte[] output = new byte[length >> 1]; for(int i = 0, j = 0; i < length; i += 2, j++) { // 转换失败,抛出 NumberFormatException 异常 output[j] = Byte.parseByte(input.substring(i, i + 2), 16); } return output; } }