ASCII Fun

ASCII art like the greeting above is common, but ASCII characters are useful for a lot more.  Represented in a Java in a manner identical to the first 128 unsigned integers, they can be substituted for ints at any time, and ints 32 -126 inclusive can be cast to chars and printed.  While limited compared to the unicode set of characters (ASCII can’t represent á, for example), ASCII is the workhorse of most file systems.

To explore the representation of ASCII a little more let’s look at it on the binary level.  To a computer, both ints and chars are represented as one byte (8 bits) of 1’s and 0’s, with each 1 or 0 representing 1 bit.

This means that when we cast an int to a char, we’re really just telling the computer “I know a char is 8 bits shorter than an int, but I only want the last (least significant) eight bits.”

To explore some of the fun things we can do with ASCII characters, let’s make an ASCII viewer program to print them out.

/**
 * Prints out all 128 ASCII characters - 63 is authentically the question mark
 */
public void printAllACSII() {
      System.out.println("All ASCII characters");
      for (int i = 0; i < 128; i++) {
        System.out.print(i + ": " + (char)i + " ");
        // Print a new line after every five characters
        if (i > 0 && i  % 5 == 0) {
          System.out.println();
        }
      }
      System.out.println();
}

 

To print out all the ASCII characters, we use a for-loop to step through all integers from 0 to 127 inclusive.  For each int, we print the int, then cast it to a char and print the char.  To keep all the characters from printing on a single line, we print a new line if i > 0 and is evenly divisible by 5 (line 32).  The “&&” is a logical AND, meaning both sides have to be true, for the condition to evaluate to true.  The modulus operator, “%”, divides the value on its left by the value on its right and returns the remainder.  At the end, we print out another blank line to move the cursor to a new line.

Let’s take a look at the results:

What’s going on here?  Five characters were supposed to print out per line, not two or three.  And what are all those squiggly question marks in boxes about?

Both 10 and 13 represent ways to enter to a new line.  ASCII 10 is the new line character “\n”, and ASCII 13 is the old carriage return.  ASCII  9 has a lot of space after it because it is the tab character or “\t”.  ASCII 0 prints out a space, the closest representation to its real value, NUL.  Those question marks inside boxes represent ASCII characters that cannot be displayed.  Some of them like BEL (ASCII 7) are leftovers from the days of telegraphs and teletype machines.  Others like DEL (ASCII 127) are simply hard to represent:  how would you represent a delete character?  

The displayable ASCII values are only 32 (the space) through 126 (tilde) inclusive.  We can print them using the method below:

public void printDisplayableASCII() {
  System.out.println("Displayable ASCII characters");
  for(int i = 32; i < 127; i++) {
    System.out.print(i + ": " + (char)i + "\t");
    // Print a new line after every five characters
    if ((i - 31) % 5 == 0) {
      System.out.println();
    }
  }
}

Print Displayable does roughly the same thing as print all, but only for characters 32 through 126 inclusive.  Instead of printing just a space after each character, we use the tab (“\t”)for this one to keep the characters aligned. Also, because we start at 32, we can get the remainder of i – 31 to determine when to print a new line.  The results after the for-loop finishes look like this:

Now all the characters printed look familiar.

We can do a lot more than just print the characters.  Because they’re represented as integers, we can treat them as such.  For example, we can add two ASCII characters and return the result as an integer as in the method below:

public int sumASCII(char ch1, char ch2) {
  return ch1 + ch2;
}

 

We can also multiply, subtract, and divide them like normal numbers.  When we try to print an ASCII character as a char that is out of range, it will display as a question mark (see main below).  

public static void main(String[] args) {
  ASCII_Viewer self = new ASCII_Viewer();
  self.printAllACSII();
  self.printDisplayableASCII();
  /* Print a "character" that is out of the ASCII range
   * It displays as a question mark.
   */
  System.out.println("128: " + (char)128);
  
  // Print out the sum of 'a' + 'A'
  System.out.println("a + A = " + self.sumASCII('a', 'A'));
  
  // Print out the product of 'a' + 'A'
  System.out.println("a * A = " + 'a' * 'A');
}

 

Download the code by clicking on one of the links below, and try seeing what you can do with ASCII characters.  If you want to see more that can be done, try checking out one of our ciphers, such as the Tradition Caesar Cipher.

Click here to download:  ASCII_Viewer.java

And here to view the code in your web browser:  ASCII_Viewer