16进制字符串和字节数组的互转


/**

*16进制字符串转为字节数组

*/

public byte[] hexToByte(String hex){

  /**

  *先去掉16进制字符串的空格

  */

  hex = hex.replace(" ","");

  /**

  *字节数组长度为16进制字符串长度的一半

  */

  int byteLength = hex.length()/2;

  byte[] bytes = new byte[byteLength];

  int m = 0;

  int n = 0;

  for(int i = 0; i<byteLength;i++){

    m = i*2+1;

    n = m+1;

    int intHex = Integer.decode("0x"+hex.substring(i * 2, m) + hex.substring(m, n));

    bytes[i] = Byte.valueOf((byte) intVal);

  }

  return bytes;

}

/**

*字节数组转为16进制字符串

*/

public static String byteToHex(byte[] bytes) {
  String strHex = "";
  StringBuilder stringBuilder = new StringBuilder();
  for (int n = 0; n < bytes.length; n++) {
    strHex = Integer.toHexString(bytes[n] & 0xFF);
    stringBuilder.append((strHex.length() == 1) ? "0" + strHex : strHex);
  }
  return stringBuilder.toString().trim();
}

 

/**

*字符串转为16进制字符串

*/

public String str2HexStr(String str) {
  char[] chars = "0123456789ABCDEF".toCharArray();
  StringBuilder sb = new StringBuilder("");
  byte[] bs = str.getBytes();
  int bit;
  for (int i = 0; i < bs.length; i++) {
    bit = (bs[i] & 0x0f0) >> 4;
    sb.append(chars[bit]);
    bit = bs[i] & 0x0f;
    sb.append(chars[bit]);
  }
  return sb.toString().trim();
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM