0
Sponsored Links


Ad by Google
Sometimes we may need to convert a Character or String to ASCII value or vice versa, So here I am going to show you a simple example to convert Character to ASCII and ASCII to Character. Also converting String to byte array and byte array to int array. In our previous post we have balanced parenthesis(very popular java coding interview) with o(n) time complexity here.

How to convert Character to ASCII

private static int charToASCII(char ch) {
  return (int) ch;
 }

How to convert ASCII to Character

private static char asciiToChar(int ascii) {
  return (char) ascii;
 }

How to convert String to ASCII byte Array

private static byte[] stringToByteArray(String value) {
  return value.getBytes(StandardCharsets.US_ASCII);
 }

How to convert String to byte Array to int Array

private static int[] byteArrayToIntArray(byte[] byteArray) {
  int[] intArray = new int[byteArray.length];
  for (int i = 0; i < byteArray.length; i++) {
   intArray[i] = byteArray[i];
  }
  return intArray;
 }

So let's see a complete example,
ASCIIExample.java
package com.javamakeuse.poc;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class ASCIIExample {
 private static int charToASCII(char ch) {
  return (int) ch;
 }

 private static char asciiToChar(int ascii) {
  return (char) ascii;
 }

 private static byte[] stringToByteArray(String value) {
  return value.getBytes(StandardCharsets.US_ASCII);
 }

 private static int[] byteArrayToIntArray(byte[] byteArray) {
  int[] intArray = new int[byteArray.length];
  for (int i = 0; i < byteArray.length; i++) {
   intArray[i] = byteArray[i];
  }
  return intArray;
 }

 public static void main(String[] args) {
  System.out.println(charToASCII('A'));
  System.out.println(charToASCII('a'));
  System.out.println(asciiToChar(charToASCII('A')));
  System.out.println(asciiToChar(charToASCII('a')));
  System.out.println(stringToByteArray("abc")[0]);
  System.out.println("*******int array**********");
  System.out.println(Arrays
    .toString(byteArrayToIntArray(stringToByteArray("abc"))));
 }
}


OUT PUT:
65
97
A
a
97
*******int array**********
[97, 98, 99]

Sponsored Links

0 comments:

Post a Comment