Convert Byte Array to Int in C#
In .NET Framework, BitConverter Class helps us to convert base Datatypes to an array of bytes and vice-versa.
GetBytes Method that takes an integer, double or other base type value is static overloaded method of BitConverter class which converts that to an array of bytes. To reverse this conversion BitConverter also has other static methods. For Example:
- ToDouble,
- ToChart,
- ToBoolean,
- ToInt16,
- ToSingle.
Code snippet below converts different integer values to a byte array and vice-versa.
namespace BitConverterExample {
class Program {
static void Main(string[] args) {
Console.WriteLine("Convert Byte Array to Int in C# and vice-versa");
// Create double to a byte array
Int32 yourInput = 235;
Console.WriteLine("Your Int value is : " + yourInput.ToString());
byte[] bytes = ConvertInt32ToByteArray(yourInput);
Console.WriteLine("Your Byte array value:");
Console.WriteLine(BitConverter.ToString(bytes));
Console.WriteLine("Your 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 param) {
return BitConverter.GetBytes(param);
}
public static byte[] ConvertIntToByteArray(Int16 param) {
return BitConverter.GetBytes(param);
}
public static byte[] ConvertIntToByteArray(Int64 param) {
return BitConverter.GetBytes(param);
}
public static byte[] ConvertIntToByteArray(int param) {
return BitConverter.GetBytes(param);
}
public static double ConvertByteArrayToInt32(byte[] param) {
return BitConverter.ToInt32(param, 0);
}
}
}
OUTPUT: