Wednesday 22 May 2019

Java: Convert String to byte array


In this post, you are going to learn,
         a. How to convert string to byte array
         b. How to specify encoding while converting string to byte array

How to convert string to byte array
String class provide 'getBytes' method to convert a string to byte array. This method encode the string to bytes using the platform's default charset.

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

How to specify encoding while converting string to byte array?
'getbytes' method is available in below overloaded forms, where you can specify the encoding (like UTF-8, ASCII) to convert the string to byte array.
public byte[] getBytes(String charsetName)
public byte[] getBytes(Charset charset)

Example
bytes = str.getBytes(Charset.forName("ASCII"));

App.java
package com.sample.app;

import java.nio.charset.Charset;

public class App {

 private static void printByteArray(byte[] bytes) {

  for (byte b : bytes) {
   System.out.print(b + " " + (char) b + "\t");
  }
  System.out.println("");
 }

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

  byte[] bytes = str.getBytes();
  printByteArray(bytes);

  bytes = str.getBytes(Charset.forName("ASCII"));
  printByteArray(bytes);

 }
}

Output
72 H  101 e 108 l  108 l  111 o 32     87 W 111 o 114 r 108 l  100 d
72 H  101 e 108 l  108 l  111 o 32     87 W 111 o 114 r 108 l  100 d

You may like
Block Chain: Create a wallet and transfer coins from one wallet to other in Java


No comments:

Post a Comment