Created
August 22, 2016 18:48
-
-
Save jpe42/89f2d10f2b7820da3ae32e374fe419e9 to your computer and use it in GitHub Desktop.
Java 9 Hex Coder
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
import java.util.PrimitiveIterator; | |
import static java.lang.Character.digit; | |
public final class Hex { | |
private Hex() {} | |
private static final char[] HEX_CHARS = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', | |
'9', 'a', 'b', 'c', 'd', 'e', 'f'}; | |
public static String encode(final byte[] data) { | |
final char[] hex = new char[data.length << 1]; | |
int index = 0; | |
for (final byte b : data) { | |
hex[index++] = HEX_CHARS[(b >> 4) & 0xF]; | |
hex[index++] = HEX_CHARS[(b & 0xF)]; | |
} | |
return new String(hex); | |
} | |
public static byte[] decode(final String hex) { | |
final int len = hex.length() >> 1; | |
final byte[] data = new byte[len]; | |
final PrimitiveIterator.OfInt codePoints = hex.codePoints().iterator(); | |
for (int i = 0;i < len;) { | |
data[i++] = (byte) (digit(codePoints.nextInt(), 16) << 4 | digit(codePoints.nextInt(), 16)); | |
} | |
return data; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment