How to convert a byte array to a hex string in Java?

后端 未结 27 3475
花落未央
花落未央 2020-11-21 04:19

I have a byte array filled with hex numbers and printing it the easy way is pretty pointless because there are many unprintable elements. What I need is the exact hexcode in

27条回答
  •  攒了一身酷
    2020-11-21 05:03

    I prefer to use this:

    final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
    public static String bytesToHex(byte[] bytes, int offset, int count) {
        char[] hexChars = new char[count * 2];
        for ( int j = 0; j < count; j++ ) {
            int v = bytes[j+offset] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }
    

    It is slightly more flexible adaptation of the accepted answer. Personally, I keep both the accepted answer and this overload along with it, usable in more contexts.

提交回复
热议问题