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

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

    I usually use the following method for debuf statement, but i don't know if it is the best way of doing it or not

    private static String digits = "0123456789abcdef";
    
    public static String toHex(byte[] data){
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i != data.length; i++)
        {
            int v = data[i] & 0xff;
            buf.append(digits.charAt(v >> 4));
            buf.append(digits.charAt(v & 0xf));
        }
        return buf.toString();
    }
    

提交回复
热议问题