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

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

    I found three different ways here: http://www.rgagnon.com/javadetails/java-0596.html

    The most elegant one, as he also notes, I think is this one:

    static final String HEXES = "0123456789ABCDEF";
    public static String getHex( byte [] raw ) {
        if ( raw == null ) {
            return null;
        }
        final StringBuilder hex = new StringBuilder( 2 * raw.length );
        for ( final byte b : raw ) {
            hex.append(HEXES.charAt((b & 0xF0) >> 4))
                .append(HEXES.charAt((b & 0x0F)));
        }
        return hex.toString();
    }
    

提交回复
热议问题