Sunday, 2 February 2020

Convert string to US_ASCII 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.US_ASCII);

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.US_ASCII);

  printByteArray(bytes);
 }

}

Output
72 101 108 108 111 32 87 111 114 108 100    

You may like

No comments:

Post a Comment