Showing posts with label US_ASCII. Show all posts
Showing posts with label US_ASCII. Show all posts

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

Saturday, 1 February 2020

Convert US_ASCII byte array to string

Following snippet converts US_ASCII byte array to string.

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

App.java
package com.sample.app;

import java.nio.charset.StandardCharsets;

public class App {

 public static void main(String[] args) {
  byte[] byteArr = {72,101,108,108,111,32,87,111,114,108,100};
  String str = new String(byteArr, StandardCharsets.US_ASCII);
  
  System.out.println(str);
  
 }

}

Output
Hello World

You may like