java实现字节数组byte[]和十六进制字符串之间的转换

java实现字节数组byte[]和十六进制字符串之间的转换

1.字节数组byte[]转换为十六进制字符串,具体代码如下所示:

public class HexUtil {
	private static final String HEX_CHARSET = "0123456789ABCDEF";
	private static final String BLANK = " ";
    /**
	  * 方法功能:字节数组byte[]转化为十六进制字符串
	  * @param byte[] b
	  * @param boolean upperCase 十六进制字符串为大写还是小写
	  * @param boolean insBlank  十六进制字符串是否用空格隔开
	  * 
	* */
	public static String byte2Hex(byte[] b, boolean upperCase, boolean insBlank){
	    if ((b == null) || (b.length == 0)) {
	      return null;
	    }
	    int size = b.length;
	    StringBuilder sb = new StringBuilder(size * 2);
	    for (int n = 0; n < size; n++)
	    {
	      if ((insBlank) && (n > 0) && (n % 4 == 0)) {
	        sb.append(" ");
	      }
	      if (upperCase) {
	        sb.append(Integer.toString((b[n] & 0xFF) + 256, 16).substring(1).toUpperCase());
	      } else {
	        sb.append(Integer.toString((b[n] & 0xFF) + 256, 16).substring(1));
	      }
	    }
	    return upperCase ? sb.toString() : sb.toString().toLowerCase();
	  }
	  public static void main(String[] args) throws UnsupportedEncodingException {
		//测试方法byte2Hex(byte[] b, boolean upperCase, boolean insBlank)
		  byte[] b = "aaaa中国加油,战胜新冠状病毒".getBytes();
		  System.out.println(byte2Hex(b, true, false));
      }
}

2.十六进制字符串转换成字节数组byte[],具体代码如下所示:

public class HexUtil {
	  private static final String HEX_CHARSET = "0123456789ABCDEF";
	  private static final String BLANK = " ";
	 /**
	   * 方法功能:将十六进制字符串转换为字节数组byte[]。
	   * @param String hexString
	   * @return byte[] 
	   * */
	  public static byte[] Hex2Bytes(String hexString){
	    byte[] arrB = hexString.getBytes();
	    int iLen = arrB.length;
	    byte[] arrOut = new byte[iLen / 2];
	    String strTmp = null;
	    for (int i = 0; i < iLen; i += 2)
	    {
	      strTmp = new String(arrB, i, 2);
	      arrOut[(i / 2)] = ((byte)Integer.parseInt(strTmp, 16));
	    }
	    return arrOut;
	  }
      public static void main(String[] args) throws UnsupportedEncodingException {
		  //测试方法Hex2Bytes(String hexString)
		  String hexString = "61616161E4B8ADE59BBDE58AA0E6B2B9EFBC8CE68898E8839CE696B0E586A0E78AB6E79785E6AF92";
		  byte[]b = Hex2Bytes(hexString);
		  System.out.println("字节数组byte[] =\n"+Arrays.toString(b));
		  String str = new String(b,"utf-8");
		  System.out.println("字节数转换为字符串:\n"+str);
      } 
}	  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值