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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.