Encoding strings as byte arrays

Add a new console application project named WorkingWithEncodings.

Import the System.Text namespace, statically import Console, and add the following statements to the Main method. The code encodes a string using the chosen encoding, loops through each byte, and then decodes back into a string and outputs it:

WriteLine("Encodings"); WriteLine("[1] ASCII"); WriteLine("[2] UTF-7"); WriteLine("[3] UTF-8"); WriteLine("[4] UTF-16 (Unicode)"); WriteLine("[5] UTF-32"); WriteLine("[any other key] Default"); // choose an encoding Write("Press a number to choose an encoding: "); ConsoleKey number = ReadKey(false).Key; WriteLine(); WriteLine(); Encoding encoder; switch (number) { case ConsoleKey.D1: encoder = Encoding.ASCII; ...

Get C# 7.1 and .NET Core 2.0 – Modern Cross-Platform Development - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.