Created
April 19, 2019 11:42
-
-
Save petergdoyle/4e74d5cce7426da165c57cae5a7e3745 to your computer and use it in GitHub Desktop.
Hex Encode Strings in 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
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