Showing posts with label UTF_16. Show all posts
Showing posts with label UTF_16. Show all posts

Wednesday, 5 February 2020

Convert string to UTF_16 byte array


String class provide 'getBytes' method, it take character set while generating the bytes from string.

Example
String str = "Hello World";
byte[] bytes = str.getBytes(StandardCharsets.UTF_16);

App.java
package com.sample.app;

import java.nio.charset.StandardCharsets;

public class App {

 private static void printByteArray(byte[] arr) {
  for (byte b : arr) {
   System.out.print(b + " ");
  }
  System.out.println();
 }

 public static void main(String args[]) {
  String str = "Hello World";

  byte[] bytes = str.getBytes(StandardCharsets.UTF_16);

  printByteArray(bytes);
 }

}

Output
-2 -1 0 72 0 101 0 108 0 108 0 111 0 32 0 87 0 111 0 114 0 108 0 100



You may like

Monday, 3 February 2020

Convert UTF_16 byte array to string

Following snippet converts UTF_16 byte array to string.

byte[] byteArr = { -2, -1, 0, 72, 0, 101, 0, 108, 0, 108, 0, 111, 0, 32, 0, 87, 0, 111, 0, 114, 0, 108, 0, 100 };
String str = new String(byteArr, StandardCharsets.UTF_16);

App.java
package com.sample.app;

import java.nio.charset.StandardCharsets;

public class App {

 public static void main(String[] args) {
  byte[] byteArr = { -2, -1, 0, 72, 0, 101, 0, 108, 0, 108, 0, 111, 0, 32, 0, 87, 0, 111, 0, 114, 0, 108, 0, 100 };
  String str = new String(byteArr, StandardCharsets.UTF_16);

  System.out.println(str);

 }

}

Output
Hello World


You may like