Convert Value Type to Byte Array and Vice Versa


Introduction

Basic data type such as bool, int, char, uint ,float etc .can be converted to byte array simply using the System.BitConverter Class provided by .net but it does not convert decimal values to byte array. In this article we will learn how to convert decimal to byte array.

Language:

C Sharp
 
Technologies:

.net 2.0/3.5
 
Implementation

First we will look at how to convert int , char,bool etc to byte array .

As I told you in introduction of this article they can be converted using System.BitConverter Class.

Here is it is how it can be done.

  /* Converting Int <-> Byte Array */

            int TestInt = 50;

            //Convert it to Byte Array

            byte[] ByteArray = BitConverter.GetBytes(TestInt);

            //Retrive Int Again from Byte Array

            int OrigionalInt =BitConverter.ToInt32(ByteArray,0);

            Console.WriteLine("Integer Retrived from Byte Array :" + OrigionalInt);

Same way you can convert others like bool,char ,int.

Now let's take a look how to work with decimal.

Decimal's little bit different from normal int to byte array we need to work with memory Stream Object and BinaryWritter.

Here is code how we can do it.

Converting Decimal to Byte Array and Vice Versa :

/* Convert Decimal <-> Byte Array */

            decimal dec = 50.50M;

            byte[] bArray= null;

            MemoryStream memStream = new MemoryStream();

            BinaryWriter writer = new BinaryWriter(memStream);

            writer.Write(dec);

            bArray = memStream.ToArray();

            memStream.Close();

            writer.Close();

            //Get Decimal Value Back From ByteArray

            MemoryStream m2 = new MemoryStream(bArray);

            BinaryReader reader = new BinaryReader(m2);

            decimal d = reader.ReadDecimal();

            m2.Close();

            reader.Close();

            Console.WriteLine("Retrived Decimal From Binary Array :" + d.ToString());

            Console.ReadKey();

Conclusion

This article shows how to convert decimal to byte array and byte array to decimal again.