Skip to content

Instantly share code, notes, and snippets.

@massimilianochiodi
Created April 15, 2022 08:38
Show Gist options
  • Save massimilianochiodi/ebc092cacb51dfc3e197e4bd799abf96 to your computer and use it in GitHub Desktop.
Save massimilianochiodi/ebc092cacb51dfc3e197e4bd799abf96 to your computer and use it in GitHub Desktop.
Byte Array to hex string and back
public static String byteArrayToHex(byte[] a) {
StringBuilder sb = new StringBuilder(a.length * 2);
for(byte b: a)
sb.append(String.format("%02x", b));
return sb.toString();
}
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len/2];
for(int i = 0; i < len; i+=2){
data[i/2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16));
}
return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment