Convert String to ASCII Java

Convert String to ASCII Java | ASCII expands as American Standard Code For Information Interchange this is widely used to transfer the information or messages between the computers & it usually contains numerical, letters, and also other symbols. ASCII is a character encoding standard for electronic exchange. The ASCII values are case-sensitive hence it has different values for the character ‘a’ and the character ‘A’.

For Example:
ASCII value for ‘A’ = 65
ASCII value for ‘B’ = 66 and so on.
See more:- Java program to display ASCII value of a given character

To convert the string to its equivalent ASCII we have to get the ASCII value of each character. Example:-
String = “KnowProgram”;
ASCII = “751101111198011411110311497109”

String To ASCII Java using String.getBytes()

In Java, the String class contains the getBytes() method which encodes given String into a sequence of bytes using the named charset, storing the result into a new byte array. The below program demonstrate the String.getBytes() method.

import java.util.Arrays;

public class Main {
   public static void main(String args[]) {
      try {
         String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
         byte[] bytes = txt.getBytes("US-ASCII");

         System.out.println("ASCII: " + 
                         Arrays.toString(bytes));
      } catch (java.io.UnsupportedEncodingException e) {
         e.printStackTrace();
      }
   }
}

Output:-

ASCII: [ 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90 ]

Using the getBytes() we can get the equivalent ASCII value of the given string by concatenating each byte value from the array. Let us see it through an example:-

import java.util.Arrays;

public class Main {
   public static void main(String args[]) {
      try {
         String txt = "KnowProgram";
         byte[] bytes = txt.getBytes("US-ASCII");
         System.out.println("Bytes array: " 
                  + Arrays.toString(bytes));

         StringBuilder sb = new StringBuilder("");
         for (byte value : bytes) {
            sb.append(value);
         }

         String ascii = sb.toString();
         System.out.println("ASCII: " + ascii);
      } catch (java.io.UnsupportedEncodingException e) {
         e.printStackTrace();
      }
   }
}

Output:-

Bytes array: [75, 110, 111, 119, 80, 114, 111, 103, 114, 97, 109]
ASCII: 751101111198011411110311497109

The same can be done without using the getBytes() method. In that case, we have to just convert char to int value and concatenate them. Below program shows it:-

String To ASCII Java without using String.getBytes()

public class Main {
   public static void main(String args[]) {
      String txt = "KnowProgram";

      StringBuilder sb = new StringBuilder("");
      for (int i = 0; i < txt.length(); i++) {
         sb.append((int) txt.charAt(i));
      }

      String ascii = sb.toString();
      System.out.println("ASCII: " + ascii);
   }
}

Output:-

ASCII: 751101111198011411110311497109

Binary String To ASCII Java

In this code, we first convert binary to decimal and then set it to the respective ASCII. 

public class Main {

   static int binToDec(String n) {
      String number = n;
      int dec = 0;
      int base = 1;

      int len = number.length();
      for (int i = len - 1; i >= 0; i--) {
         if (number.charAt(i) == '1')
            dec += base;
         base = base * 2;
      }

      return dec;
   }

   static String stringtoASCII(String str) {
      int N = (str.length());
      if (N % 8 != 0) {
         return "Not Possible!";
      }

      String res = "";
      for (int i = 0; i < N; i += 8) {
         int decimal_value = binToDec((str.substring(i, 8 + i)));

         res += decimal_value;
      }

      return res;
   }

   public static void main(String[] args) {
      String s = "0110000101100010";
      System.out.print(stringtoASCII(s));

   }
}

Output:-

9798

Java Convert ASCII To String

Previously we have converted String to ASCII equivalent and binary string to ASCII equivalent. Now let us see its reverse operation. We will convert ASCII equivalent to string format. But before let us see a simple program to convert an ASCII value to a string:-

public class Main{
   public static void main(String[] args) {
      int val = 65;
      String string = String.valueOf((char) val);
      System.out.println(string);
   }
}

Output:-

A

ASCII values of alphabets belong from 32 to 122. Hence we will get a digit from the ASCII equivalent and form the number. If the number belongs between the 32 to 122 range then we will convert them into characters. Let us see the example.

Program to Convert ASCII to String in Java

public class Main {
   public static void main(String[] args) {
      String ascii = "751101111198011411110311497109";
      String string = asciiToSentence(ascii, ascii.length());
      System.out.println("String: " + string);
   }

   public static String asciiToSentence(String ascii, int length) {
      int num = 0;
      StringBuilder sb = new StringBuilder("");
      for (int i = 0; i < length; i++) {
         num = num * 10 + (ascii.charAt(i) - '0');
         // If num is within the range
         if (num >= 32 && num <= 122) {
            sb.append((char) num);
            num = 0;
         }
      }
      return sb.toString();
   }
}

Output:-

String: KnowProgram

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *