Convert different data types to byte array and convert byte array back : BitConverter « Development « C# / CSharp Tutorial






using System;
using System.Net;
using System.Text;

class MainClass
{
   public static void Main()
   {
      int test1 = 45;
      double test2 = 3.14159;
      int test3 = -1234567890;
      bool test4 = false;
      byte[] data = new byte[1024];
      string output;

      data = BitConverter.GetBytes(test1);
      output = BitConverter.ToString(data);
      Console.WriteLine("test1 = {0}, string = {1}", test1, output);

      data = BitConverter.GetBytes(test2);
      output = BitConverter.ToString(data);
      Console.WriteLine("test2 = {0}, string = {1}", test2, output);

      data = BitConverter.GetBytes(test3);
      output = BitConverter.ToString(data);
      Console.WriteLine("test3 = {0}, string = {1}", test3, output);

      data = BitConverter.GetBytes(test4);
      output = BitConverter.ToString(data);
      Console.WriteLine("test4 = {0}, string = {1}", test4, output);
   }
}
test1 = 45, string = 2D-00-00-00
test2 = 3.14159, string = 6E-86-1B-F0-F9-21-09-40
test3 = -1234567890, string = 2E-FD-69-B6
test4 = False, string = 00








14.19.BitConverter
14.19.1.BitConverter
14.19.2.Convert a bool to a byte array and display
14.19.3.Convert a byte array to a bool and display
14.19.4.Convert an int to a byte array and display
14.19.5.Convert a byte array to an int and display
14.19.6.Convert different data types to byte array and convert byte array back