Last active
November 4, 2021 12:59
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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