Java

[Java] byte array to String, String to byte array

Darane 2021. 9. 3. 15:04

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(); 
}
반응형