Files
elink-online-common/src/main/java/com/eactive/eai/util/HexaConverter.java
T

63 lines
1.9 KiB
Java

package com.eactive.eai.util;
public class HexaConverter {
public static final String bytesToHexa(byte[] abyte) {
StringBuilder s = new StringBuilder();
if (abyte == null)
return s.toString();
for (int i = 0; i < abyte.length; i++) {
s.append( Integer.toHexString((abyte[i] & 0xf0) >> 4) )
.append( Integer.toHexString(abyte[i] & 0xf));
}
return s.toString();
}
public static final byte[] hexaToBytes(String hexa) {
if((hexa.length() % 2) != 0) return null;
byte[] bytes = new byte[hexa.length() / 2];
String hexaBytes = null;
for(int i=0; i <bytes.length;i++) {
hexaBytes = hexa.substring(i*2, i*2+2);
int byteBit = Integer.parseInt(hexaBytes, 16);
bytes[i] = (byte)byteBit;
}
return bytes;
}
public static String binToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
sb.append(String.format("%02X", b));
}
return sb.toString();
}
public static byte[] hexToBin(String hexStr) {
String lookup = "0123456789ABCDEF";
int len = hexStr.length();
byte[] bArray = new byte[len / 2];
for (int i = 0; i < bArray.length; i++) {
char highChar = Character.toUpperCase(hexStr.charAt(i * 2));
char lowChar = Character.toUpperCase(hexStr.charAt(i * 2 + 1));
int high = lookup.indexOf(highChar);
int low = lookup.indexOf(lowChar);
bArray[i] = (byte) ((high << 4) | low);
}
return bArray;
}
// public static void main(String[] argv) {
// String str = "TEST\nÇѱÛ";
// String hexStr = HexaConverter.bytesToHexa(str.getBytes());
// System.out.println(hexStr);
// System.out.println(new String(HexaConverter.hexaToBytes(hexStr), Charset.forName("euc-kr") ) );
// System.out.println(new String(HexaConverter.hexaToBytes(hexStr)) );
// }
}