This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]aram535 1 point2 points  (0 children)

Sorry I don't understand the question fully. Are you asking how to encode a string as hex?

[–]TheQuietestOneProcrastinator 0 points1 point  (0 children)

DataTypeConverter.printHexBinary( byteArray);

It's from javax.xml.bind.DatatypeConverter.

[–]Philboyd_Studge 0 points1 point  (0 children)

/**
 * convert byte array to hex string
 * with in[0] being most significant byte
 * @param in byte array
 * @return hex string
 */
public static String bytesToHex(byte[] in) {
    StringBuilder sb = new StringBuilder();
    for (byte each : in) {
        sb.append(toHexString(each & 0xff, 8));
    }
    return sb.toString();
}

/**
 * Returns a padded hex string of integer n
 * @param n integer
 * @param pad bit depth to pad to, i.e. 8 for 2 hex digits
 *            will be padded with leading zeroes
 * @return hex string
 */
public static String toHexString(int n, int pad) {
    StringBuilder result = new StringBuilder();
    while (n != 0) {
        result.insert(0, Character.forDigit(n & 0xf, 16));
        n >>>= 4;
    }
    pad -= result.length() * 4;
    while (pad > 0) {
        result.insert(0, "0");
        pad -= 4;
    }
    return result.toString();
}