In Java, we can cast the char to int to get the ASCII value of the char.

char aChar = 'a';
//int ascii = (int) aChar;      // explicitly cast, optional, improves readability
int ascii = aChar;              // implicit cast, auto cast char to int,
System.out.println(ascii);      // 97

The explicit cast (int)char is optional, if we assign a char to an integer, Java will auto-cast the char to an int.

1. Convert Char to ASCII

This Java example converts a char to an ASCII value, and we can use Character.toChars to turn the ASCII value back to a character.

package com.mkyong.basic;

public class JavaAsciiExample1 {

    public static void main(String[] args) {

        // convert char to ASCII
        char aChar = 'a';
        int ascii = aChar;              // auto cast char to int
        System.out.println(ascii);      // 97

        // convert ASCII to char
        char[] chars = Character.toChars(ascii);
        System.out.println(chars);      // a

        char aChar2 = (char) ascii;     // or downcast int to char, it works.
        System.out.println(aChar2);     // a
    }
}

Output

97
a
a

In ASCII, decimal from 0 to 31, and 127 represents file-related stuff; the printable characters are from 32 to 126. To convert ASCII back to a char or string, we can do a simple range check validation to ensure it’s a valid ASCII value.

public static char asciiToChar(final int ascii) {

    if (ascii < 0 || ascii >= 127) {
        throw new IllegalArgumentException("Invalid ASCII value!");
    }

    return (char) ascii;
}

2. Convert String to ASCII

2.1 We can use String.getBytes(StandardCharsets.US_ASCII) to convert the string into a byte arrays byte[], and upcast the byte to int to get the ASCII value.

package com.mkyong.basic;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class JavaAsciiExample2 {

    public static void main(String[] args) {

        String input = "abcdefg";
        byte[] bytes = input.getBytes(StandardCharsets.US_ASCII);

                                                    // print the first byte
        System.out.println(bytes[0]);               // 97

        List<Integer> result = new ArrayList<>();   // convert bytes to ascii
        for (byte aByte : bytes) {
            int ascii = (int) aByte;                // byte -> int
            result.add(ascii);
        }

        System.out.println(result.toString());      // [97, 98, 99, 100, 101, 102, 103]

    }

}

Output

97
[97, 98, 99, 100, 101, 102, 103]

2.2 Java 9, there is a new API String.char() to convert string into a InputStream, follow by a .boxed(), and it will convert into a Stream<Integer>

String input = "abcdefg";
List<Integer> collect = input
                            .chars()                        // IntStream
                            .boxed()                        // Stream<Integer>, ASCII values
                            .collect(Collectors.toList());  // Returns a List

collect.forEach(System.out::println);

Output

97
98
99
100
101
102
103

2.3 To convert ASCII values back to a string, we can use Character.toString, it accepts an integer (code point) as an argument and returns a string.

package com.mkyong.basic;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class JavaAsciiExample3 {

    public static void main(String[] args) {

        List<Integer> ascii = Arrays.asList(97, 98, 99, 100, 101, 102, 103);

        // Java 8 stream
        String result = ascii.stream()
                .map(x -> Character.toString(x))    // int -> string
                .collect(Collectors.joining());     // return a string

        System.out.println(result);
    }

}

Output:

abcdefg

References

Laisser un commentaire