2019년 9월 21일 토요일

[Java] HexString to Byte, Byte to HexString

HexString to Byte, Byte to HexString 변환 예제 이다.


public static byte[] hexStringToByte(String hex){
 if (hex == null || hex.length() == 0)
  return null;
  
 if( hex.length() % 2 != 0 )
  hex = "0" + hex;

 byte[] ba = new byte[hex.length() / 2];
 for (int i = 0; i < ba.length; i++)
  ba[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);

 return ba;
}

public static String byteToHexString(byte[] bytes) {
 char[] container = new char[bytes.length * 2];

 for (int i = 0; i < bytes.length; i++) {
  int b = bytes[i] & 0xFF;
  container[i * 2] = Character.forDigit(b >>> 4, 0x10);
  container[i * 2 + 1] = Character.forDigit(b & 0xF, 0x10);
 }

 return new String(container);
}


댓글 없음:

댓글 쓰기