Permalink
Cannot retrieve contributors at this time
Fetching contributors…
| // <Snippet8> | |
| using System; | |
| using System.Text; | |
| public class Example | |
| { | |
| public static void Main() | |
| { | |
| string[] strings= { "This is the first sentence. ", | |
| "This is the second sentence. " }; | |
| Encoding asciiEncoding = Encoding.ASCII; | |
| // Create array of adequate size. | |
| byte[] bytes = new byte[49]; | |
| // Create index for current position of array. | |
| int index = 0; | |
| Console.WriteLine("Strings to encode:"); | |
| foreach (var stringValue in strings) { | |
| Console.WriteLine(" {0}", stringValue); | |
| int count = asciiEncoding.GetByteCount(stringValue); | |
| if (count + index >= bytes.Length) | |
| Array.Resize(ref bytes, bytes.Length + 50); | |
| int written = asciiEncoding.GetBytes(stringValue, 0, | |
| stringValue.Length, | |
| bytes, index); | |
| index = index + written; | |
| } | |
| Console.WriteLine("\nEncoded bytes:"); | |
| Console.WriteLine("{0}", ShowByteValues(bytes, index)); | |
| Console.WriteLine(); | |
| // Decode Unicode byte array to a string. | |
| string newString = asciiEncoding.GetString(bytes, 0, index); | |
| Console.WriteLine("Decoded: {0}", newString); | |
| } | |
| private static string ShowByteValues(byte[] bytes, int last ) | |
| { | |
| string returnString = " "; | |
| for (int ctr = 0; ctr <= last - 1; ctr++) { | |
| if (ctr % 20 == 0) | |
| returnString += "\n "; | |
| returnString += String.Format("{0:X2} ", bytes[ctr]); | |
| } | |
| return returnString; | |
| } | |
| } | |
| // The example displays the following output: | |
| // Strings to encode: | |
| // This is the first sentence. | |
| // This is the second 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 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 | |
| // | |
| // Decoded: This is the first sentence. This is the second sentence. | |
| // </Snippet8> |