Java code To convert byte to Hexadecimal

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

    Try this way:

    byte bv = 10;
    String hexString = Integer.toHexString(bv);
    

    Dealing with array (if I understood you correctly):

    byte[] bytes = {9, 10, 11, 15, 16};
    StringBuffer result = new StringBuffer();
    for (byte b : bytes) {
        result.append(String.format("%02X ", b));
        result.append(" "); // delimiter
    }
    return result.toString();
    

    As polygenelubricants mentioned, String.format() is the right answer compare to Integer.toHexString() (since it deals with negative numbers in a right way).

提交回复
热议问题