Java code To convert byte to Hexadecimal

后端 未结 19 2448
我寻月下人不归
我寻月下人不归 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:45

    This is the code that I've found to run the fastest so far. I ran it on 109015 byte arrays of length 32, in 23ms. I was running it on a VM so it'll probably run faster on bare metal.

    public static final char[] HEX_DIGITS =         {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    
    public static char[] encodeHex( final byte[] data ){
        final int l = data.length;
        final char[] out = new char[l<<1];
        for( int i=0,j=0; i>> 4];
            out[j++] = HEX_DIGITS[0x0F & data[i]];
        }
        return out;
    }
    

    Then you can just do

    String s = new String( encodeHex(myByteArray) );
    

提交回复
热议问题