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

后端 未结 27 3242
花落未央
花落未央 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
    
    0 讨论(0)
  • 2020-11-21 04:47

    From the discussion here, and especially this answer, this is the function I currently use:

    private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
    public static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = HEX_ARRAY[v >>> 4];
            hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
        }
        return new String(hexChars);
    }
    

    My own tiny benchmarks (a million bytes a thousand times, 256 bytes 10 million times) showed it to be much faster than any other alternative, about half the time on long arrays. Compared to the answer I took it from, switching to bitwise ops --- as suggested in the discussion --- cut about 20% off of the time for long arrays. (Edit: When I say it's faster than the alternatives, I mean the alternative code offered in the discussions. Performance is equivalent to Commons Codec, which uses very similar code.)

    2k20 version, with respect to Java 9 compact strings:

    private static final byte[] HEX_ARRAY = "0123456789ABCDEF".getBytes(StandardCharsets.US_ASCII);
    public static String bytesToHex(byte[] bytes) {
        byte[] hexChars = new byte[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = HEX_ARRAY[v >>> 4];
            hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
        }
        return new String(hexChars, StandardCharsets.UTF_8);
    }
    
    0 讨论(0)
  • 2020-11-21 04:47

    // Shifting bytes is more efficient // You can use this one too

    public static String getHexString (String s) 
    {
        byte[] buf = s.getBytes();
    
        StringBuffer sb = new StringBuffer();
    
        for (byte b:buf)
        {
            sb.append(String.format("%x", b));
        }
    
    
            return sb.toString();
    }
    
    0 讨论(0)
  • 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();
    }
    
    0 讨论(0)
  • 2020-11-21 04:48
    Converts bytes data to hex characters
    
    @param bytes byte array to be converted to hex string
    @return byte String in hex format
    
    private static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        int v;
        for (int j = 0; j < bytes.length; j++) {
            v = bytes[j] & 0xFF;
            hexChars[j * 2] = HEX_ARRAY[v >>> 4];
            hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
        }
        return new String(hexChars);
    }
    
    0 讨论(0)
  • 2020-11-21 04:50

    If you're using the Spring Security framework, you can use:

    import org.springframework.security.crypto.codec.Hex
    
    final String testString = "Test String";
    final byte[] byteArray = testString.getBytes();
    System.out.println(Hex.encode(byteArray));
    
    0 讨论(0)
提交回复
热议问题