Advertisement
kyrathasoft

char2byte.cs

May 27th, 2019
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. using System;
  2. using System.Text;
  3.  
  4. namespace CharToByteEncodingAndTheReverse{
  5.  
  6. static class Constants {
  7. public const string CSHARP = "C# Programming";
  8. public const string PI = "Value PI =~ 3.14159";
  9. }
  10.  
  11. class DoSomeEncoding {
  12.  
  13. static void Main() {
  14.  
  15. ResetConsole();
  16.  
  17. Console.Write("\n This program demonstrates conversion of characters to their respective byte encodings,");
  18. Console.Write("\n and, conversely, byte encoded characters back into characters forming strings...\n");
  19.  
  20. DemoChar2ByteEncoding();
  21. DemoCharByteArrayToString();
  22.  
  23. }
  24.  
  25. static void DemoChar2ByteEncoding(){
  26. Console.Write("\n Press a key to see the following string of characters (in yellow) encoded to bytes...\n");
  27. Console.ForegroundColor = ConsoleColor.Yellow;
  28. Console.Write("\n {0} ", Constants.CSHARP);
  29. Console.ForegroundColor = ConsoleColor.Cyan;
  30.  
  31. Console.ReadKey();
  32. Console.WriteLine();
  33. Console.Write(" ");
  34. byte[] bt = Encoding.Default.GetBytes(Constants.CSHARP);
  35. WriteByteArrayValuesToConsole(bt, false);
  36. Console.WriteLine();
  37. Console.ForegroundColor = ConsoleColor.White;
  38. }
  39.  
  40. static void DemoCharByteArrayToString(){
  41. Console.Write("\n Press a key to convert the byte-encoded characters (in yellow) back into a string...\n\n");
  42. Console.ForegroundColor = ConsoleColor.Yellow;
  43. byte[] bt = Encoding.Default.GetBytes(Constants.PI);
  44. WriteByteArrayValuesToConsole(bt, false);
  45. Console.ReadKey();
  46. Console.WriteLine();
  47. Console.Write(" ");
  48. Console.ForegroundColor = ConsoleColor.Cyan;
  49. WriteByteArrayValuesToConsole(bt, true);
  50. Console.ForegroundColor = ConsoleColor.White;
  51. Console.WriteLine();
  52. }
  53.  
  54. static void ResetConsole(){
  55. Console.Clear();
  56. Console.ForegroundColor = ConsoleColor.Blue;
  57. Console.BackgroundColor = ConsoleColor.Gray;
  58. Console.Write("\n char2byte.exe ");
  59. Console.Write("\n 27th May 2019 ");
  60. Console.Write("\n Bryan Miller ");
  61. Console.Write("kyrathasoft@gmail.com \n");
  62. Console.ForegroundColor = ConsoleColor.White;
  63. Console.BackgroundColor = ConsoleColor.Black;
  64. }
  65.  
  66. static void WriteByteArrayValuesToConsole(byte[] b, bool convertToCharacters)
  67. {
  68. foreach(byte _b in b){
  69. if(!convertToCharacters){
  70. Console.Write("{0}", _b.ToString() + " ");
  71. }else{
  72. Console.Write("{0}", Convert.ToChar(_b) + " ");
  73. }
  74. }
  75. }
  76.  
  77. }
  78.  
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement