Skip to content

Instantly share code, notes, and snippets.

@nickfox
Created Feb 15, 2011
Embed
What would you like to do?
public static String bytesToHex(byte[] data) {
if (data==null) {
return null;
} else {
int len = data.length;
String str = "";
for (int i=0; i<len; i++) {
if ((data[i]&0xFF)<16) {
str = str + "0" + java.lang.Integer.toHexString(data[i]&0xFF);
} else {
str = str + java.lang.Integer.toHexString(data[i]&0xFF);
}
}
return str;
}
}
public static byte[] hexToBytes(String str) {
if (str==null) {
return null;
} else if (str.length() < 2) {
return null;
} else {
int len = str.length() / 2;
byte[] buffer = new byte[len];
for (int i=0; i<len; i++) {
buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
}
return buffer;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment