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

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

    My solution is based on maybeWeCouldStealAVan's solution, but does not rely on any additionaly allocated lookup tables. It does not uses any 'int-to-char' casts hacks (actually, Character.forDigit() does it, performing some comparison to check what the digit truly is) and thus might be a bit slower. Please feel free to use it wherever you want. Cheers.

    public static String bytesToHex(final byte[] bytes)
    {
        final int numBytes = bytes.length;
        final char[] container = new char[numBytes * 2];
    
        for (int i = 0; i < numBytes; i++)
        {
            final int b = bytes[i] & 0xFF;
    
            container[i * 2] = Character.forDigit(b >>> 4, 0x10);
            container[i * 2 + 1] = Character.forDigit(b & 0xF, 0x10);
        }
    
        return new String(container);
    }
    

提交回复
热议问题