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.");
-
- 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:");
-
- 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);
- }
- }
- }