The BitConverter.ToInt16() method in C# is used to return a 16-bit signed integer converted from two bytes at a specified position in a byte array.
The syntax is as follows −
public static short ToInt16 (byte[] val, int begnIndex);
Above, val is the byte array, whereas begnIndex is the beginning position within val.
Let us now see an example −
using System; public class Demo { public static void Main(){ byte[] arr = { 0, 0, 7, 10, 18, 20, 25, 26, 32}; Console.WriteLine("Byte Array = {0} ", BitConverter.ToString(arr)); for (int i = 1; i < arr.Length - 1; i = i + 2) { short res = BitConverter.ToInt16(arr, i); Console.WriteLine("\nValue = "+arr[i]); Console.WriteLine("Result = "+res); } } }
This will produce the following output −
Byte Array = 00-00-07-0A-12-14-19-1A-20 Value = 0 Result = 1792 Value = 10 Result = 4618 Value = 20 Result = 6420 Value = 26 Result = 8218
Let us now see another example −
using System; public class Demo { public static void Main(){ byte[] arr = { 10, 20, 30}; Console.WriteLine("Byte Array = {0} ", BitConverter.ToString(arr)); for (int i = 1; i < arr.Length - 1; i = i + 2) { short values = BitConverter.ToInt16(arr, i); Console.WriteLine("\nValue = "+arr[i]); Console.WriteLine("Result = "+values); } } }
This will produce the following output −
Byte Array = 0A-14-1E Value = 20 Result = 7700