Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Text;
- namespace CharToByteEncodingAndTheReverse{
- static class Constants {
- public const string CSHARP = "C# Programming";
- public const string PI = "Value PI =~ 3.14159";
- }
- class DoSomeEncoding {
- static void Main() {
- ResetConsole();
- Console.Write("\n This program demonstrates conversion of characters to their respective byte encodings,");
- Console.Write("\n and, conversely, byte encoded characters back into characters forming strings...\n");
- DemoChar2ByteEncoding();
- DemoCharByteArrayToString();
- }
- static void DemoChar2ByteEncoding(){
- Console.Write("\n Press a key to see the following string of characters (in yellow) encoded to bytes...\n");
- Console.ForegroundColor = ConsoleColor.Yellow;
- Console.Write("\n {0} ", Constants.CSHARP);
- Console.ForegroundColor = ConsoleColor.Cyan;
- Console.ReadKey();
- Console.WriteLine();
- Console.Write(" ");
- byte[] bt = Encoding.Default.GetBytes(Constants.CSHARP);
- WriteByteArrayValuesToConsole(bt, false);
- Console.WriteLine();
- Console.ForegroundColor = ConsoleColor.White;
- }
- static void DemoCharByteArrayToString(){
- Console.Write("\n Press a key to convert the byte-encoded characters (in yellow) back into a string...\n\n");
- Console.ForegroundColor = ConsoleColor.Yellow;
- byte[] bt = Encoding.Default.GetBytes(Constants.PI);
- WriteByteArrayValuesToConsole(bt, false);
- Console.ReadKey();
- Console.WriteLine();
- Console.Write(" ");
- Console.ForegroundColor = ConsoleColor.Cyan;
- WriteByteArrayValuesToConsole(bt, true);
- Console.ForegroundColor = ConsoleColor.White;
- Console.WriteLine();
- }
- static void ResetConsole(){
- Console.Clear();
- Console.ForegroundColor = ConsoleColor.Blue;
- Console.BackgroundColor = ConsoleColor.Gray;
- Console.Write("\n char2byte.exe ");
- Console.Write("\n 27th May 2019 ");
- Console.Write("\n Bryan Miller ");
- Console.Write("kyrathasoft@gmail.com \n");
- Console.ForegroundColor = ConsoleColor.White;
- Console.BackgroundColor = ConsoleColor.Black;
- }
- static void WriteByteArrayValuesToConsole(byte[] b, bool convertToCharacters)
- {
- foreach(byte _b in b){
- if(!convertToCharacters){
- Console.Write("{0}", _b.ToString() + " ");
- }else{
- Console.Write("{0}", Convert.ToChar(_b) + " ");
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement