[转] java byte[] hex打印


import
javax.xml.bind.DatatypeConverter; import java.io.UnsupportedEncodingException; public class test { public static void main(String[] args) throws UnsupportedEncodingException{ //print hex string version of HELLO WORLD byte[] helloBytes = "HELLO WORLD".getBytes(); String helloHex = DatatypeConverter.printHexBinary(helloBytes); System.out.printf("Hello hex: 0x%s\n", helloHex); //convert hex-encoded string back to original string byte[] decodedHex = DatatypeConverter.parseHexBinary(helloHex); String decodedString = new String(decodedHex, "UTF-8"); System.out.printf("Hello decoded : %s\n", decodedString); } }
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    for ( int j = 0; j < bytes.length; j++ ) {
        int v = bytes[j] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return new String(hexChars);
}
private static final char[] hexCode = "0123456789ABCDEF".toCharArray();

    public String printHexBinary(byte[] data) {
        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();
    }

转自:http://blog.csdn.net/x_iya/article/details/54136799

posted @ 2017-07-19 23:19  未命名blogs  阅读(3287)  评论(0编辑  收藏  举报