Java String Hex 轉換

覺得 String.format("%1$02x", b) 很神奇, 隨手記錄一下

String to Hex


public static String toHex(byte[] bytes) {
    StringBuilder sb = new StringBuilder();
    for (byte b : bytes) {
        sb.append(String.format("%1$02x", b));
    }
    return sb.toString();
}

Hex to String


import java.io.UnsupportedEncodingException;
import javax.xml.bind.DatatypeConverter;

public static String hexToString(String hexStr) throws UnsupportedEncodingException {
    byte[] bytes = DatatypeConverter.parseHexBinary(hexStr);
    return new String(bytes, "UTF-8");
}

沒有留言:

張貼留言