DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Simple Toolkit For Translation Between Byte Array And Hex String
// description of your code here
package flib.util;
import java.util.Locale;
/**
* BD : Simple Kit for translation between byte array and hex string.
* @author John-Lee
*/
public class HexByteKit {
private static byte charToByte(char c){
return (byte) "0123456789ABCDEF".indexOf(c);
}
/**
* BD : Used to transfer hex string into byte array. two hex string combines one byte. So that means the length of hex string
* should be even. Or the null will be returned.
* @param hexStr
* @return
*/
public static byte[] hex2byte(String hexStr) {
if(hexStr == null || hexStr.isEmpty() || (hexStr.length()%2>1)) {
return null;
}
String hexStrUp = hexStr.toUpperCase();
int length = hexStrUp.length()/2;
char[] hexChars = hexStrUp.toCharArray();
byte[] resultByte = new byte[length];
for(int i=0;i<length;i++) {
int pos = i*2;
resultByte[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos+1]));
}
return resultByte;
}
/**
* BD : Used to transfer byte array into hex string.
* @param b
* @return
*/
public static String byte2hex(byte[] b){
StringBuffer hexStr= new StringBuffer("");
String stmp = "";
for(int i=0;i<b.length;i++) {
stmp = (java.lang.Integer.toHexString(b[i] & 0xFF));
if(stmp.length() == 1) {
hexStr.append("0"+stmp);
} else {
hexStr.append(stmp);
}
}
return hexStr.toString().toUpperCase();
}
public static void main(String args[]) {
byte[] b = {(byte)0xaa,(byte)0x1f,(byte)0x2b,(byte)0x14};
String hexStr = byte2hex(b);
System.out.println("Hex string :"+hexStr);
byte[] tmp = hex2byte(hexStr);
boolean tres = true;
if(b.length == tmp.length) {
for(int i=0;i<tmp.length;i++) {
if(b[i] != tmp[i]) {
tres = false;
break;
}
}
}else {
tres = false;
}
if(tres) {
System.out.println("Translation success");
} else {
System.err.println("Translation failed");
}
}
}





