private static String convertToHexString(byte[] data, String append) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length; i++) {
int halfbyte = (data[i] >>> 4) & 0x0F;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9))
buf.append((char) ('0' + halfbyte));
else
buf.append((char) ('a' + (halfbyte - 10)));
halfbyte = data[i] & 0x0F;
} while(two_halfs++ < 1);
if(append != null)
buf.append(append);
}
return buf.toString();
}
Another Similar program:
http://www.baeldung.com/sha-256-hashing-java
private static String bytesToHex(byte[] hash) {
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if(hex.length() == 1)
hexString.append('0');
hexString.append(hex);
//hexString.append(' ');
}
return hexString.toString();
}
Output:
System.out.println("HexText: "+bytesToHex(data));
HexText: 13 0a 63 00 14 00 12 00 09 37 38 36 31 32 33 34 35 36
You can use constructor of String, which takes byte array and character encoding
This is the right way to convert bytes to String, provided you know for sure that bytes are encoded in the character encoding you are using.
Read more: https://javarevisited.blogspot.com/2014/08/2-examples-to-convert-byte-array-to-String-in-Java.html#ixzz5kn8lnEZi
System.out.println("HexText: "+bytesToHex(data));
HexText: 13 0a 63 00 14 00 12 00 09 37 38 36 31 32 33 34 35 36
You can use constructor of String, which takes byte array and character encoding
String str = new String(bytes, "UTF-8");
This is the right way to convert bytes to String, provided you know for sure that bytes are encoded in the character encoding you are using.
Read more: https://javarevisited.blogspot.com/2014/08/2-examples-to-convert-byte-array-to-String-in-Java.html#ixzz5kn8lnEZi
- StandardCharsets.ISO_8859_1
- StandardCharsets.US_ASCII
- StandardCharsets.UTF_16
- StandardCharsets.UTF_16BE
- StandardCharsets.UTF_16LE
To view the Binary encoded Base64 in Hex String ....