Skip to content

Instantly share code, notes, and snippets.

@jvorhauer
Last active November 4, 2021 12:59
Show Gist options
  • Save jvorhauer/d383915a525e56e9a908396ecc8d545b to your computer and use it in GitHub Desktop.
Save jvorhauer/d383915a525e56e9a908396ecc8d545b to your computer and use it in GitHub Desktop.
[convert bytes to hex string] Convert any byte array to a hex string #java
String bytesToHex(byte[] bytes) {
char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars);
}
// or
String bytesToHex(byte[] hash) {
StringBuilder hexString = new StringBuilder(2 * hash.length);
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if(hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment