Tuesday, May 13, 2014

ASCII - Char conversion in Java

This is the ASCII to Char mapping table :



We can convert a char to its ASCII equivalent and ASCII back to a char in java.

  char a= 'a';   
  System.out.println((int) a);   

prints 97 in the console.


ASCII to char:
 int dotAscii = 46;   
 System.out.println((char) dotAscii);   

prints '.' in the console.


Now we know that char can be converted to ASCII and vice versa.

1) Convert a string to ASCII.

 public static void convertStringTosASCII(String input) {  
  char[] inputArray = input.toCharArray(); // Convert string to char array.  
  StringBuilder sb = new StringBuilder();  
  for (int i = 0; i < inputArray.length; i++) {  
      sb.append((int) inputArray[i]); //Append the ascii code of the character array to the string builder  
  }  
  System.out.println(sb.toString());  
  }  

we give "Test String" as the input the output will be "841011151163283116114105110103"

2) Convert ASCII to String

 public static void convertASCIIToString(String input) {  
  StringBuilder sb = new StringBuilder();  
  for (int i = 0; i < input.length(); i += 2) {  
   String temp = input.substring(i, i + 2);  
   int string_ascii = Integer.parseInt(temp);  
   if (string_ascii < 32) {            // ASCII code for characters ranges from 32-127. It                                           can be either 2-digit or 3-digit.  
   temp = input.substring(i, i + 3);  
   string_ascii = Integer.parseInt(temp);  
   i = i + 1;  
   }  
   sb.append((char) string_ascii); //append the char to the string builder  
  }  
  System.out.println(sb.toString());  
  }  

if we give "841011151163283116114105110103" as input then we get "Test String" as the output.



No comments:

Post a Comment