Java code To convert byte to Hexadecimal

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

    This is a very fast way. No external libaries needed.

    final protected static char[] HEXARRAY = "0123456789abcdef".toCharArray();
    
        public static String encodeHexString( 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] = HEXARRAY[v >>> 4];
                hexChars[j * 2 + 1] = HEXARRAY[v & 0x0F];
            }
            return new String(hexChars);
        }
    

提交回复
热议问题