String To Byte Array In Java
Chapter:
String Handling
Last Updated:
04-08-2016 20:06:46 UTC
Program:
/* ............... START ............... */
public class JavaStringToByteArray {
public static void main(String[] args) {
String content = "Welcome To JavaScan.com";
byte[] bytes = content.getBytes();
System.out.println("String: " + content);
for (int x : bytes) {
System.out.println((char) x + ": " + x);
}
}
}
/* ............... END ............... */
Output
String: Welcome To JavaScan.com
W: 87
e: 101
l: 108
c: 99
o: 111
m: 109
e: 101
: 32
T: 84
o: 111
: 32
J: 74
a: 97
v: 118
a: 97
S: 83
c: 99
a: 97
n: 110
.: 46
c: 99
o: 111
m: 109
Notes:
-
The reason the Charset version is favoured, is that all String objects in Java are stored internally as UTF-16. When converting to a byte[] you will get a different breakdown of bytes for the given glyphs of that String , depending upon the chosen charset. You can use String.getBytes() which returns the byte[] array.
Tags
String To Byte Array, Java