Skip to content

Instantly share code, notes, and snippets.

@petergdoyle
Created April 19, 2019 11:42
Show Gist options
  • Save petergdoyle/4e74d5cce7426da165c57cae5a7e3745 to your computer and use it in GitHub Desktop.
Save petergdoyle/4e74d5cce7426da165c57cae5a7e3745 to your computer and use it in GitHub Desktop.
Hex Encode Strings in Java
public class HexEncoder {
public static void main(String[] args) {
System.out.printf("String:%s HexEncoded: %s\n", "hello world", hexEncode("hello world".getBytes()));
}
static private String hexEncode(byte[] input) {
StringBuilder result = new StringBuilder();
char[] digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
for (int idx = 0; idx < input.length; ++idx) {
byte b = input[idx];
result.append(digits[(b & 0xf0) >> 4]);
result.append(digits[b & 0x0f]);
}
return result.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment