December 28, 2020 Today I learned how to convert a string to byte type in Java, so I will summarize it.
One of the primitive types, which stores values up to 8 bits. Since 1 bit is 0 or 1, 1 byte can represent a bit array from 00000000 to 11111111. Since the byte type is signed and takes a negative value, it takes a value from -128 to 127. Since image files, audio files, and character strings are also a collection of bytes internally, they are often used as a collection of binary data as a byte array rather than handling byte type variables alone.
Use the getBytes () method. The getBytes () method converts a string into a set of bytes and returns it as a byte array.
Basic writing
str.getBytes("Encode");
Sample code
public class Sample {
public static void main(String[] args) throws InterruptedException, UnsupportedEncodingException {
String str = "The string you want to convert";
byte[] def = str.getBytes();
byte[] utf8 = str.getBytes("UTF-8");
byte[] utf16 = str.getBytes("UTF-16");
System.out.println(Arrays.toString(def));
System.out.println(Arrays.toString(utf8));
System.out.println(Arrays.toString(utf16));
}
}
Execution result
[-27, -92, -119, -26, -113, -101, -29, -127, -105, -29, -127, -97, -29, -127, -124, -26, -106, -121, -27, -83, -105, -27, -120, -105]
[-27, -92, -119, -26, -113, -101, -29, -127, -105, -29, -127, -97, -29, -127, -124, -26, -106, -121, -27, -83, -105, -27, -120, -105]
[-2, -1, 89, 9, 99, -37, 48, 87, 48, 95, 48, 68, 101, -121, 91, 87, 82, 23]
Recommended Posts