C# BitConverter ToInt32
Description
BitConverter ToInt32
returns a 32-bit signed integer
converted from four bytes at a specified position in a byte array.
Syntax
BitConverter.ToInt32
has the following syntax.
public static int ToInt32(
byte[] value,
int startIndex
)
Parameters
BitConverter.ToInt32
has the following parameters.
value
- An array of bytes.startIndex
- The starting position within value.
Returns
BitConverter.ToInt32
method returns A 32-bit signed integer formed by four bytes beginning at startIndex.
Example
The following example uses the ToInt32 method to create Int32 values from a four-byte array and from the upper four bytes of an eight-byte array.
/*from w w w . j av a 2 s . c o m*/
using System;
public class Example
{
public static void Main()
{
Byte[] bytes1 = { 0xEC, 0x00, 0x00, 0x00 };
Console.WriteLine("{0}--> 0x{1:X4} ({1:N0})", FormatBytes(bytes1),
BitConverter.ToInt32(bytes1, 0));
Byte[] bytes2 = BitConverter.GetBytes(Int64.MaxValue / 2);
Console.WriteLine("{0}--> 0x{1:X4} ({1:N0})", FormatBytes(bytes2),
BitConverter.ToInt32(bytes2, 4));
int original = (int) Math.Pow(16, 3);
Byte[] bytes3 = BitConverter.GetBytes(original);
int restored = BitConverter.ToInt32(bytes3, 0);
Console.WriteLine("0x{0:X4} ({0:N0}) --> {1} --> 0x{2:X4} ({2:N0})", original,
FormatBytes(bytes3), restored);
}
private static string FormatBytes(Byte[] bytes)
{
string value = "";
foreach (var byt in bytes)
value += String.Format("{0:X2} ", byt);
return value;
}
}
The code above generates the following result.