During the implementation of the program, if the part that transmits data is processed as a byte array, it may need to be converted to a String.
Let's look at an example of converting a byte array to String in Java. We will also look at an example of converting a byte array to a Hexadecimal String.
1. Convert byte array to String
This is an example of converting byte array to String. As in the example below, if a byte array is entered as an argument of the String constructor, it is returned as a String.
byte[] byteArray = {0x48, 0x65, (byte)0x6C, (byte)0x6C, (byte)0x6f, 0x20, 0x57, (byte)0x6f, 0x72, (byte)0x6c, 0x64};
String data = new String(byteArray);
System.out.println(data);
Result
Hello World
2. Convert String to byte array
This is an example of converting String to byte array. If you use String's getBytes() API, you can see that the string value of String is converted to a byte array as shown below.
String data = "Hello World";
System.out.println (data.getBytes ()); // byte array output
System.out.println (byteArrayToHexaString (data.getBytes ())); // Output byte array as hexadecimal string
Result
[B@3d075dc0
48 65 6C 6C 6F 20 57 6F 72 6C 64
3. Convert byte array to hexadecimal string
This is an example of displaying the value of byte array as a hexadecimal string for human readability.
If you want to know the value of the byte array when logging for debugging, this is a good example.
public static String byteArrayToHexaString(byte[] bytes) {
StringBuilder builder = new StringBuilder();
for (byte data : bytes) {
builder.append(String.format("%02X ", data));
}
return builder.toString();
}
'Java' 카테고리의 다른 글
com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $ 해결하기 (0) | 2021.09.02 |
---|---|
[Java] InputStream을 byte 배열(byte[])로 변환 (0) | 2021.09.02 |
[Java] Ping 보내는 방법 InetAddress.isReachable() (0) | 2021.09.02 |
[Java] Float, Double 크기 비교(compare) (0) | 2021.08.29 |
[Java] String startsWith(), EndsWith() 구현 예제 (0) | 2020.07.20 |
[Java] JSONArray에서 JSONObject 값 얻어오기 (0) | 2020.07.12 |
[Java] java.lang.ArrayIndexOutOfBoundsException (0) | 2020.06.13 |
Java String을 int로 변환, int를 String으로 변환 - String to int, int to String (0) | 2020.05.27 |