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

后端 未结 27 3466
花落未央
花落未央 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:57

    private static String bytesToHexString(byte[] bytes, int length) {
            if (bytes == null || length == 0) return null;
    
            StringBuilder ret = new StringBuilder(2*length);
    
            for (int i = 0 ; i < length ; i++) {
                int b;
    
                b = 0x0f & (bytes[i] >> 4);
                ret.append("0123456789abcdef".charAt(b));
    
                b = 0x0f & bytes[i];
                ret.append("0123456789abcdef".charAt(b));
            }
    
            return ret.toString();
        }
    

提交回复
热议问题