Skip to content

Instantly share code, notes, and snippets.

@mirjalal
Created April 10, 2017 16:37
Show Gist options
  • Save mirjalal/dc1e3ff9764fecc848dc23a8fc09c5bf to your computer and use it in GitHub Desktop.
Save mirjalal/dc1e3ff9764fecc848dc23a8fc09c5bf to your computer and use it in GitHub Desktop.
Convert hex to binary
/**
* Converts hex string to byte array.
*
* @param hex hex string. if invalid, return null.
* @return binary data.
*/
private static byte[] hexStr2Bin(String hex) {
int sz = hex.length()/2;
byte[] b = new byte[hex.length()/2];
for (int i=0;i<sz;i++) {
try {
b[i] = (byte)Integer.parseInt(hex.substring(i*2, i*2+2), 16);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
return b;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment