Convert Basic Value Types to Byte Arrays - CSharp File IO

CSharp examples for File IO:MemoryStream

Description

Convert Basic Value Types to Byte Arrays

Demo Code

using System;//from  w  ww  .  j a v a  2s.com
using System.IO;
class MainClass
{
   public static byte[] DecimalToByteArray (decimal src)
   {
      using (MemoryStream stream = new MemoryStream())
      {
         using (BinaryWriter writer = new BinaryWriter(stream))
         {
            writer.Write(src);
            return stream.ToArray();
         }
      }
   }
   public static decimal ByteArrayToDecimal (byte[] src)
   {
      using (MemoryStream stream = new MemoryStream(src))
      {
         using (BinaryReader reader = new BinaryReader(stream))
         {
            return reader.ReadDecimal();
         }
      }
   }
   public static void Main()
   {
      byte[] b = null;
      // Convert a bool to a byte array and display.
      b = BitConverter.GetBytes(true);
      Console.WriteLine(BitConverter.ToString(b));
      // Convert a byte array to a bool and display.
      Console.WriteLine(BitConverter.ToBoolean(b,0));
      // Convert an int to a byte array and display.
      b = BitConverter.GetBytes(1234);
      Console.WriteLine(BitConverter.ToString(b));
      // Convert a byte array to an int and display.
      Console.WriteLine(BitConverter.ToInt32(b,0));
      // Convert a decimal to a byte array and display.
      b = DecimalToByteArray(28512312345545.5631231236696m);
      Console.WriteLine(BitConverter.ToString(b));
      // Convert a byte array to a decimal and display.
      Console.WriteLine(ByteArrayToDecimal(b));
   }
}

Result


Related Tutorials