SIGN UP MEMBER LOGIN:    
ARTICLE

Convert Byte Array to Int in C#

Posted by Mahesh Chand Articles | C# Language February 10, 2010
The code snippet in this article converts different integer values to a byte array and vice-versa using BitConverter class.
Reader Level:

The BitConverter class in .NET Framework is provides functionality to convert base data types to an array of bytes, and an array of bytes to base data types.

The BitConverter class has a static overloaded GetBytes method that takes an integer, double or other base type value and convert that to a array of bytes. The BitConverter class also have other static methods to reverse this conversion. Some of these methods are ToDouble, ToChart, ToBoolean, ToInt16, and ToSingle.

The following code snippet converts different integer values to a byte array and vice-versa.

namespace BitConverterSample

{

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("Int and byte arrays conversion sample.");

            // Create double to a byte array

            Int32 i32 = 125;

            Console.WriteLine("Int value: " + i32.ToString());

            byte[] bytes = ConvertInt32ToByteArray(i32);

            Console.WriteLine("Byte array value:");

            Console.WriteLine(BitConverter.ToString(bytes));

 

            Console.WriteLine("Byte array back to Int32:");

            // Create byte array to Int32

            double dValue = ConvertByteArrayToInt32(bytes);

            Console.WriteLine(dValue.ToString());

 

            Console.ReadLine();

 

       }

 

        public static byte[] ConvertInt32ToByteArray(Int32 I32)

        {

            return BitConverter.GetBytes(I32);

        }

        public static byte[] ConvertIntToByteArray(Int16 I16)

        {

            return BitConverter.GetBytes(I16);

        }

        public static byte[] ConvertIntToByteArray(Int64 I64)

        {

            return BitConverter.GetBytes(I64);

        }

        public static byte[] ConvertIntToByteArray(int I)

        {

            return BitConverter.GetBytes(I);

        }

     

 

        public static double ConvertByteArrayToInt32(byte[] b)

        {

            return BitConverter.ToInt32(b, 0);

        }

    }

}

Login to add your contents and source code to this article
share this article :
post comment
 
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Team Foundation Server Hosting
Become a Sponsor