Java code To convert byte to Hexadecimal

后端 未结 19 2531
我寻月下人不归
我寻月下人不归 2020-11-22 17:26

I have an array of bytes. I want each byte String of that array to be converted to its corresponding hexadecimal values.

Is there any function in Java to convert a b

19条回答
  •  天命终不由人
    2020-11-22 17:52

    The fastest way i've yet found to do this is the following:

    private static final String    HEXES    = "0123456789ABCDEF";
    
    static String getHex(byte[] raw) {
        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();
    }
    

    It's ~ 50x faster than String.format. if you want to test it:

    public class MyTest{
        private static final String    HEXES        = "0123456789ABCDEF";
    
        @Test
        public void test_get_hex() {
            byte[] raw = {
                (byte) 0xd0, (byte) 0x0b, (byte) 0x01, (byte) 0x2a, (byte) 0x63,
                (byte) 0x78, (byte) 0x01, (byte) 0x2e, (byte) 0xe3, (byte) 0x6c,
                (byte) 0xd2, (byte) 0xb0, (byte) 0x78, (byte) 0x51, (byte) 0x73,
                (byte) 0x34, (byte) 0xaf, (byte) 0xbb, (byte) 0xa0, (byte) 0x9f,
                (byte) 0xc3, (byte) 0xa9, (byte) 0x00, (byte) 0x1e, (byte) 0xd5,
                (byte) 0x4b, (byte) 0x89, (byte) 0xa3, (byte) 0x45, (byte) 0x35,
                (byte) 0xd6, (byte) 0x10,
            };
    
            int N = 77777;
            long t;
    
            {
                t = System.currentTimeMillis();
                for (int i = 0; i < N; i++) {
                    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)));
                    }
                    hex.toString();
                }
                System.out.println(System.currentTimeMillis() - t); // 50
            }
    
            {
                t = System.currentTimeMillis();
                for (int i = 0; i < N; i++) {
                    StringBuilder hex = new StringBuilder(2 * raw.length);
                    for (byte b : raw) {
                        hex.append(String.format("%02X", b));
                    }
                    hex.toString();
                }
                System.out.println(System.currentTimeMillis() - t); // 2535
            }
    
        }
    }
    

    Edit: Just found something just a lil faster and that holds on one line but is not compatible with JRE 9. Use at your own risks

    import javax.xml.bind.DatatypeConverter;
    
    DatatypeConverter.printHexBinary(raw);
    

提交回复
热议问题