February 5, 2000 - The ASCII Standard | WebReference

February 5, 2000 - The ASCII Standard

Yehuda Shiran February 5, 2000
The ASCII Standard
Tips: February 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

The ASCII format is a standard for internal representation of characters. For example, the A character is internally represented in the computer by the ASCII value of 64, while the Z character is represented by 90. There are two basic functions to convert characters to their ASCII values and vice versa. The function charCodeAt(i) is a String method which converts the ith character to its ASCII value. The function fromCharCode(d) is also a String method which converts the ASCII value of d to a character.

Here is an example that uses these two functions. It implements a simple text encoding, designed to hide content of a message from casual users. It replaces each alphabetical character in the input text by its "complementary" character: A by Z, B by Y, etc:

function complement(s) {
  var sResult = "";
  var i = 0;
  var d = 0;
  
  for (i = 0; i < s.length; i++) {
    d = s.charCodeAt(i);
	if ((d >= 65) && (d <= 90)) {
	  d = 90 - (d -65);
    }
	sResult += String.fromCharCode(d);
  }
  return sResult;
}

And here is how you call this function to encode it twice:

var s = "A SECRET MESSAGE! ";
window.alert(s);
var sEncoded = complement(s);
window.alert(sEncoded);
s = complement(sEncoded);
window.alert(s);

The second encoding should give you the original message.

Learn more about the ASCII standard and its new replacement, the Unicode, in our Column 25, Unicode.