JAVA byte数组转化为16进制字符串输出

时间:2021-10-11 20:59:58

最简单的方法:

利用javax.xml.bind包下的DatatypeConverter

printHexBinary

public static java.lang.String printHexBinary(byte[] val)

Converts an array of bytes into a string.

Parameters:
val - An array of bytes
Returns:
A string containing a lexical representation of xsd:hexBinary
Throws:
IllegalArgumentException - if val is null.
import javax.xml.bind.DatatypeConverter;
import java.io.UnsupportedEncodingException;
public class test {
public static void main(String[] args) throws UnsupportedEncodingException{
//print hex string version of HELLO WORLD
byte[] helloBytes = "HELLO WORLD".getBytes();
String helloHex = DatatypeConverter.printHexBinary(helloBytes);
System.out.printf("Hello hex: 0x%s\n", helloHex); //convert hex-encoded string back to original string
byte[] decodedHex = DatatypeConverter.parseHexBinary(helloHex);
String decodedString = new String(decodedHex, "UTF-8");
System.out.printf("Hello decoded : %s\n", decodedString);
}
}

JAVA byte数组转化为16进制字符串输出

或者使用*提供的方法,貌似最快

final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(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);
}

又或者使用java源码:

D:\JAVA\jdk1.8.0_65\src\javax\xml\bind\DatatypeConverterImpl.java

private static final char[] hexCode = "0123456789ABCDEF".toCharArray();

    public String printHexBinary(byte[] data) {
StringBuilder r = new StringBuilder(data.length * 2);
for (byte b : data) {
r.append(hexCode[(b >> 4) & 0xF]);
r.append(hexCode[(b & 0xF)]);
}
return r.toString();
}