Convert String to Octet String in Java

Published by user on

In this post, we will look at how to convert String to Octet String in Java.

Octet string basically means byte array.

Program

Let’s have a look at the program.

import java.nio.charset.StandardCharsets;
import java.util.Arrays;

// Java program to demonstrate
// the how to convert
// string to octet string
public class OctetString {
        public static void main(String[] args) {
                // this string contains
                // important data
                String str = "importanData";
                // byte array representation
                // of string
                byte[] octetStr = str.getBytes(StandardCharsets.US_ASCII);
                System.out.println("Byte Array Representation is :");
                System.out.println(Arrays.toString(octetStr));
        }
}

Output:

Byte Array Representation is :
[105, 109, 112, 111, 114, 116, 97, 110, 68, 97, 116, 97]
Categories: Java