[72, 105, 32, 104, 101, 108, 108, 111]
- Is it what you'd like to see out of that string Hi Hello
?
Then do that:
String str = "Hi hello";
byte[] bytes = str.getBytes();
// convert
Byte[] bytesWrap = new Byte[bytes.length];
for (int i = 0; i < bytes.length; i++) {
bytesWrap[i] = bytes[i];
}
String bytesStr = Arrays.asList(bytesWrap).toString();
//print result
System.out.println("bytes in \"" + str + "\":" + bytesStr);
UPDATED: Explanation:
default implementation of java.util.List.toString() produces string like [ element.toString(),element.toString() ...]
Then there is a java.utils.Arrays
utilitiy which can convert array to list, but... elements must be Objects, not primitives.
So, steps are
1. convert from byte[]
to corresponding Object wrapper Byte[]
2. convert Byte[]
to List
3. Use List.toString()
Of course it is just a demonstration how to use List to simply print Array which is good for objects.
For that particular case with primitives there is more simple code.
String str = "Hi hello";
StringBuilder bytesStrBuilder =new StringBuilder("[ ");
for (byte bt:str.getBytes()) {
bytesStrBuilder.append(bt).append(" ");
}
String bytesStr = bytesStrBuilder.append("]").toString();
System.out.println("bytes in \"" + str + "\":" + bytesStr);