« Looking for a Good "Hit in Crotch" Movie? | Main | Seattle Weather Forecasts »

December 16, 2005

Converting between characters and their ASCII value in Monad

For some reason a lot of the programs I write need to convert between a character and its ASCII value (like "A" to 65 and back). In C this was easy because a string was an array of chars and a single char could be treated as an int, but as we move into languages that try to blur the distinction between char and string (or between char and string and int, as Perl does), you need more explicit ways to convert. Especially if your language doesn't support declaring ranges with characters like ("A".."Z").

In Monad, you might think you could just do [int]"A", but this gives an error:

MSH> [int]"A"
Cannot convert "A" to "System.Int32". Error: "Input string was not in a correct format."
At line:1 char:6
+ [int]" <<<< A"

What you have to do instead is first convert the string to a char, and then you can change it to an int:

MSH> [int][char]"A"

(Before you ask, I'll explain that the casting of a string to a char will fail if the string isn't one character long:)

MSH> [int][char]"AB"
Cannot convert "AB" to "System.Char". Error: "String must be exactly one character long."
At line:1 char:12
+ [int][char]" <<<< AB"

To go the other way, you can't just cast the number directly to a string, because then it will convert it to its string representation:

MSH> [string]65
MSH> $([string]65).GetType().FullName

So what you do is cast the number back to char:

MSH> [char]65

Arugably you should go all the way and cast that entire thing to a string (as in [string][char]65), but Monad will treat a char like a string in most cases. So in the string to char to int conversion you need to explicitly cast it all the way to an int or it will "tip" back to being a string, but going from int to string you can stop at char and Monad will do the rest.

As a test, understanding that the EndsWith() method on System.String takes a string argument, and "HA".EndsWith("A") is true, which of the following is true:

  1. "HA".EndsWith(65)
  2. "HA".EndsWith([char]65)
  3. "HA".EndsWith([string]65)

The answer (no peeking) is #2; it successfully converts 65 to a char "A", which is then automatically converted to a string "A". The others both pass the string "65" as an argument and therefore return false.

Posted by AdamBa at December 16, 2005 03:40 PM

Trackback Pings

TrackBack URL for this entry: