public static String encode(byte[] bytes) {final int length = bytes.length;
// | BigInteger constructor throws if it is given an empty array.if (length == 0) {return "00";}
return new BigInteger(bytes).toString(16);}
public static String toHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
if (bytes != null)for (byte b:bytes) {
final String hexString = Integer.toHexString(b & 0xff);
if(hexString.length()==1)sb.append('0');
sb.append(hexString);//.append(' ');}
return sb.toString();//.toUpperCase();}
要使用DatatypeConver:
public String toHexString(byte... bytes) {
return Optional.ofNullable(bytes).filter(bs->bs.length>0).map(DatatypeConverter::printHexBinary).map(str->IntStream.range(0, str.length()).filter(i->(i%2)==0) // take every second index.mapToObj(i->"0x" + str.substring(i, i+2)).collect(Collectors.joining(" "))).orElse("");}
+-------------------------------------------------+| 0 1 2 3 4 5 6 7 8 9 a b c d e f |+--------+-------------------------------------------------+----------------+|00000010| 40 40 b3 f3 80 f3 80 f3 80 f1 48 f1 41 f1 4e f1 |@@........H.A.N.||00000020| 47 f1 49 f1 4e f1 47 b5 f1 52 f1 4f f1 43 f1 4b |G.I.N.G..R.O.C.K||00000030| f3 80 f3 80 41 b4 40 40 f3 80 f3 80 40 f3 80 04 |....A.@@....@...|+--------+-------------------------------------------------+----------------+
byte[] arr;//set it to your valueStringBuilder sb=new StringBuilder(arr.length*2);//1 byte...2 hex digitsfor(int i=0;i<arr.length;i++){sb.append(Integer.toString(arr[i],16));}String hexValue=sb.toString();