Permalink
Cannot retrieve contributors at this time
Fetching contributors…
| // <Snippet9> | |
| using System; | |
| using System.Text; | |
| public class Example | |
| { | |
| public static void Main() | |
| { | |
| string[] strings = { "This is the first sentence. ", | |
| "This is the second sentence. ", | |
| "This is the third sentence. " }; | |
| Encoding asciiEncoding = Encoding.ASCII; | |
| // Array to hold encoded bytes. | |
| byte[] bytes; | |
| // Array to hold decoded characters. | |
| char[] chars = new char[50]; | |
| // Create index for current position of character array. | |
| int index = 0; | |
| foreach (var stringValue in strings) { | |
| Console.WriteLine("String to Encode: {0}", stringValue); | |
| // Encode the string to a byte array. | |
| bytes = asciiEncoding.GetBytes(stringValue); | |
| // Display the encoded bytes. | |
| Console.Write("Encoded bytes: "); | |
| for (int ctr = 0; ctr < bytes.Length; ctr++) | |
| Console.Write(" {0}{1:X2}", | |
| ctr % 20 == 0 ? Environment.NewLine : "", | |
| bytes[ctr]); | |
| Console.WriteLine(); | |
| // Decode the bytes to a single character array. | |
| int count = asciiEncoding.GetCharCount(bytes); | |
| if (count + index >= chars.Length) | |
| Array.Resize(ref chars, chars.Length + 50); | |
| int written = asciiEncoding.GetChars(bytes, 0, | |
| bytes.Length, | |
| chars, index); | |
| index = index + written; | |
| Console.WriteLine(); | |
| } | |
| // Instantiate a single string containing the characters. | |
| string decodedString = new string(chars, 0, index - 1); | |
| Console.WriteLine("Decoded string: "); | |
| Console.WriteLine(decodedString); | |
| } | |
| } | |
| // The example displays the following output: | |
| // String to Encode: This is the first sentence. | |
| // Encoded bytes: | |
| // 54 68 69 73 20 69 73 20 74 68 65 20 66 69 72 73 74 20 73 65 | |
| // 6E 74 65 6E 63 65 2E 20 | |
| // | |
| // String to Encode: This is the second sentence. | |
| // Encoded bytes: | |
| // 54 68 69 73 20 69 73 20 74 68 65 20 73 65 63 6F 6E 64 20 73 | |
| // 65 6E 74 65 6E 63 65 2E 20 | |
| // | |
| // String to Encode: This is the third sentence. | |
| // Encoded bytes: | |
| // 54 68 69 73 20 69 73 20 74 68 65 20 74 68 69 72 64 20 73 65 | |
| // 6E 74 65 6E 63 65 2E 20 | |
| // | |
| // Decoded string: | |
| // This is the first sentence. This is the second sentence. This is the third sentence. | |
| // </Snippet9> |