This little code example shows a String to byte array conversion. The String class has a method called getBytes which returns an array of bytes. In the example the length of the array is printed out to illustrate that the length of the array is the same as the number of characters in the String.
package org.best.example;
public class Main {
/*
* This method converts a String to an array of bytes
*/
public void convertStringToByteArray() {
String stringToConvert = "This String is 76 characters long and will be converted to an array of bytes";
byte[] theByteArray = stringToConvert.getBytes();
System.out.println(theByteArray.length);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().convertStringToByteArray();
}
}
package org.best.example;
public class Main {
/*
* This method converts a String to an array of bytes
*/
public void convertStringToByteArray() {
String stringToConvert = "This String is 76 characters long and will be converted to an array of bytes";
byte[] theByteArray = stringToConvert.getBytes();
System.out.println(theByteArray.length);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().convertStringToByteArray();
}
}
No comments:
Post a Comment