How to convert a byte array to a hex string in Java?

后端 未结 27 3467
花落未央
花落未央 2020-11-21 04:19

I have a byte array filled with hex numbers and printing it the easy way is pretty pointless because there are many unprintable elements. What I need is the exact hexcode in

27条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-21 04:59

    The method javax.xml.bind.DatatypeConverter.printHexBinary(), part of the Java Architecture for XML Binding (JAXB), was a convenient way to convert a byte[] to a hex string. The DatatypeConverter class also included many other useful data-manipulation methods.

    In Java 8 and earlier, JAXB was part of the Java standard library. It was deprecated with Java 9 and removed with Java 11, as part of an effort to move all Java EE packages into their own libraries. It's a long story. Now, javax.xml.bind doesn't exist, and if you want to use JAXB, which contains DatatypeConverter, you'll need to install the JAXB API and JAXB Runtime from Maven.

    Example usage:

    byte bytes[] = {(byte)0, (byte)0, (byte)134, (byte)0, (byte)61};
    String hex = javax.xml.bind.DatatypeConverter.printHexBinary(bytes);
    

    Will result in:

    000086003D
    

    This answer the same as this one.

提交回复
热议问题