# Get-AsciiEncoding.ps1
# Sample using PowerShell
# Thomas Lee - tfl@psp.co.uk
$ascii = new-object System.Text.ASCIIEncoding
# A Unicode string with two characters outside the ASCII code range
$unicodeString = "Pi (Π) and Sigma (♥)"
"Original string ({0} chars long):`n{1}" -f $unicodestring.length,$unicodeString
# Save positions of the special characters for later reference.
$indexOfPi = $unicodeString.IndexOf('Π')
$indexOfSigma = $unicodeString.IndexOf('♥')
"Pi is at position m: {0}" -f $indexofpi
"Sigma is at position: {0}" -f $indexofsigma
# Encode string
$encodedBytes = $ascii.GetBytes($unicodeString)
""
"Encoded bytes:"
foreach ($b in $encodedBytes) {"[{0}]" -f $b }
""
# Notice that the special characters have been replaced with
# the value 63, which is the ASCII character code for '?'.
""
"Value at position of Pi character : {0}" -f $encodedBytes[$indexOfPi]
"Value at position of Sigma character: {0}" -f $encodedBytes[$indexOfSigma]
# Decode bytes back to string.
# Notice missing Pi and Sigma characters.
$decodedString = $ascii.GetString($encodedBytes)
""
"Decoded string:"
$decodedString
This script produces the following output:
PS C:\Users\tfl>
C:\foo\Get-AsciiEncoding.ps1
Original string (20 chars long):
Pi (Π) and Sigma (♥)
Pi is at position m: 4
Sigma is at position: 18
Encoded bytes:
[80]
[105]
[32]
[40]
[63]
[41]
[32]
[97]
[110]
[100]
[32]
[83]
[105]
[103]
[109]
[97]
[32]
[40]
[63]
[41]
Value at position of Pi character : 63
Value at position of Sigma character: 63
Decoded string:
Pi (?) and Sigma (?)