Java Data Type How to - Convert UTF-16BE string to byte for








Question

We would like to know how to convert UTF-16BE string to byte for.

Answer

/* w  ww  .ja  v a  2s. co m*/
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;

public class Main {
  public static void main(String[] args) throws Exception {
    String os = "abc";
    for (byte b : os.getBytes("UTF-16BE")) {
      System.out.println(b);
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);
    for (char c : os.toCharArray()) {
      dos.writeChar(c);
    }

    byte[] ba = baos.toByteArray();

    for (byte b : ba) {
      System.out.println(b);
    }
  }
}