
cz.d1x.dxcrypto.common.HexConverter Maven / Gradle / Ivy
package cz.d1x.dxcrypto.common;
/**
* Class for hex conversions.
*
* Extracted from javax.xml.bind.DatatypeConverterImpl
*/
public final class HexConverter {
private static final char[] hexCode = "0123456789ABCDEF".toCharArray();
/**
* Converts an array of bytes into a string.
*
* @param data An array of bytes
* @return A string containing a lexical representation of hex binary
* @throws IllegalArgumentException if data is null.
*/
public static String printHexBinary(byte[] data) {
if (data == null) {
throw new IllegalArgumentException("data cannot be null");
}
StringBuilder r = new StringBuilder(data.length * 2);
for (byte b : data) {
r.append(hexCode[(b >> 4) & 0xF]);
r.append(hexCode[(b & 0xF)]);
}
return r.toString();
}
/**
* Converts the string argument into an array of bytes.
*
* @param hex A string containing lexical representation of
* hex binary.
* @return An array of bytes represented by the string argument.
* @throws IllegalArgumentException if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:hexBinary.
*/
public static byte[] parseHexBinary(String hex) {
final int len = hex.length();
// "111" is not a valid hex encoding.
if (len % 2 != 0) {
throw new IllegalArgumentException("hexBinary needs to be even-length: " + hex);
}
byte[] out = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
int h = hexToBin(hex.charAt(i));
int l = hexToBin(hex.charAt(i + 1));
if (h == -1 || l == -1) {
throw new IllegalArgumentException("contains illegal character for hexBinary: " + hex);
}
out[i / 2] = (byte) (h * 16 + l);
}
return out;
}
private static int hexToBin(char ch) {
if ('0' <= ch && ch <= '9') {
return ch - '0';
}
if ('A' <= ch && ch <= 'F') {
return ch - 'A' + 10;
}
if ('a' <= ch && ch <= 'f') {
return ch - 'a' + 10;
}
return -1;
}
}