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

后端 未结 27 4244
花落未央
花落未央 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 04:44

    A small variant of the solution proposed by @maybewecouldstealavan, which lets you visually bundle N bytes together in the output hex string:

     final static char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
     final static char BUNDLE_SEP = ' ';
    
    public static String bytesToHexString(byte[] bytes, int bundleSize /*[bytes]*/]) {
            char[] hexChars = new char[(bytes.length * 2) + (bytes.length / bundleSize)];
            for (int j = 0, k = 1; j < bytes.length; j++, k++) {
                    int v = bytes[j] & 0xFF;
                    int start = (j * 2) + j/bundleSize;
    
                    hexChars[start] = HEX_ARRAY[v >>> 4];
                    hexChars[start + 1] = HEX_ARRAY[v & 0x0F];
    
                    if ((k % bundleSize) == 0) {
                            hexChars[start + 2] = BUNDLE_SEP;
                    }   
            }   
            return new String(hexChars).trim();    
    }
    

    That is:

    bytesToHexString("..DOOM..".toCharArray().getBytes(), 2);
    2E2E 444F 4F4D 2E2E
    
    bytesToHexString("..DOOM..".toCharArray().getBytes(), 4);
    2E2E444F 4F4D2E2E
    

提交回复
热议问题