Java code To convert byte to Hexadecimal

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

    A short and simple way to convert byte[] to hex string by using BigInteger:

    import java.math.BigInteger;
    
    byte[] bytes = new byte[] {(byte)255, 10, 20, 30};
    String hex = new BigInteger(1, bytes).toString(16);
    System.out.println(hex); // ff0a141e
    

    How It Works?

    The built-in system class java.math.BigInteger class (java.math.BigInteger) is compatible with binary and hex data:

    • Its has a constructor BigInteger(signum=1, byte[]) to create a big integer by byte[] (set its first parameter signum = 1 to handle correctly the negative bytes)
    • Use BigInteger.toString(16) to convert the big integer to hex string
    • To parse a hex number use new BigInteger("ffa74b", 16) - does not handle correctly the leading zero

    If you may want to have the leading zero in the hex result, check its size and add the missing zero if necessary:

    if (hex.length() % 2 == 1)
        hex = "0" + hex;
    

    Notes

    Use new BigInteger(1, bytes), instead of new BigInteger(bytes), because Java is "broken by design" and the byte data type does not hold bytes but signed tiny integers [-128...127]. If the first byte is negative, the BigInteger assumes you pass a negative big integer. Just pass 1 as first parameter (signum=1).

    The conversion back from hex to byte[] is tricky: sometimes a leading zero enters in the produced output and it should be cleaned like this:

    byte[] bytes = new BigInteger("ffa74b", 16).toByteArray();
    if (bytes[0] == 0) {
        byte[] newBytes = new byte[bytes.length - 1];
        System.arraycopy(bytes, 1, newBytes, 0, newBytes.length);
        bytes = newBytes;
    }
    

    The last note is the if the byte[] has several leading zeroes, they will be lost.

提交回复
热议问题