BitConverter.ToInt32() Method in C#


The BitConverter.ToInt32() method in C# is used to return a 32-bit signed integer converted from four bytes at a specified position in a byte array.

Syntax

The syntax is as follows −

public static int ToInt32 (byte[] val, int begnIndex);

Above, val is the byte array, whereas begnIndex is the beginning position within val.

Example

Let us now see an example −

 Live Demo

using System;
public class Demo {
   public static void Main(){
      byte[] arr = { 10, 20, 30, 40, 50};
      Console.WriteLine("Byte Array = {0} ", BitConverter.ToString(arr));
      for (int i = 1; i < arr.Length - 3; i = i + 4) {
         int res = BitConverter.ToInt32(arr, i);
         Console.WriteLine("\nValue = "+arr[i]);
         Console.WriteLine("Result = "+res);
      }
   }
}

Output

This will produce the following output −

Byte Array = 0A-14-1E-28-32
Value = 20
Result = 841489940

Example

Let us now see another example −

 Live Demo

using System;
public class Demo {
   public static void Main(){
      byte[] arr = { 0, 0, 10, 15, 20, 26, 32, 34, 40};
      Console.WriteLine("Byte Array = {0} ", BitConverter.ToString(arr));
      for (int i = 1; i < arr.Length - 3; i = i + 4) {
         int res = BitConverter.ToInt32(arr, i);
         Console.WriteLine("\nValue = "+arr[i]);
         Console.WriteLine("Result = "+res);
      }
   }
}

Output

This will produce the following output −

Byte Array = 00-00-0A-0F-14-1A-20-22-28
Value = 0
Result = 336529920
Value = 26
Result = 673325082
raja
Published on 03-Dec-2019 08:05:42
Advertisements