简体   繁体   中英

Java: How to reverse this byte[] to hex method?

I found this online and it works for what I need it for but how do I reverse it, meaning how to I convert the hex string back into a byte[]?

private static final char[] HEX_CHARS = {
    '0', '1', '2' ,'3', '4', '5', '6', '7', '8', '9',
    'a', 'b', 'c', 'd', 'e', 'f'
};

public String toHexString(byte[] bytes)
{
    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < bytes.length; i++) {
        byte b = bytes[i];
        sb.append(new char[] {HEX_CHARS[(b >> 4) & 0x0f], HEX_CHARS[b & 0x0f]});
    }

    return sb.toString();
}

Try following:

public static byte[] hexStringToByteArray(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                             + Character.digit(s.charAt(i+1), 16));
    }
    return data;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM