Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
BitConverter.ToInt16() Method in C#
The BitConverter.ToInt16() method in C# is used to convert two consecutive bytes from a byte array into a 16-bit signed integer (short). This method reads bytes in little-endian format, where the first byte represents the lower-order bits and the second byte represents the higher-order bits.
Syntax
Following is the syntax for the BitConverter.ToInt16() method −
public static short ToInt16(byte[] value, int startIndex);
Parameters
value − The byte array containing the bytes to convert.
startIndex − The starting position within the byte array from which to begin reading two bytes.
Return Value
Returns a 16-bit signed integer (short) formed by combining two bytes starting at the specified index.
Example 1: Converting Multiple Byte Pairs
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("\nBytes at index {0}-{1}: {2:X2} {3:X2}",
i, i+1, arr[i], arr[i+1]);
Console.WriteLine("Result = {0}", res);
}
}
}
The output of the above code is −
Byte Array = 00-00-07-0A-12-14-19-1A-20 Bytes at index 1-2: 00 07 Result = 1792 Bytes at index 3-4: 0A 12 Result = 4618 Bytes at index 5-6: 14 19 Result = 6420 Bytes at index 7-8: 1A 20 Result = 8218
Example 2: Simple Byte Pair Conversion
using System;
public class Demo {
public static void Main() {
byte[] arr = { 10, 20, 30 };
Console.WriteLine("Byte Array = {0}", BitConverter.ToString(arr));
short value = BitConverter.ToInt16(arr, 1);
Console.WriteLine("\nConverting bytes at index 1-2:");
Console.WriteLine("Byte 1: {0} (0x{0:X2})", arr[1]);
Console.WriteLine("Byte 2: {0} (0x{0:X2})", arr[2]);
Console.WriteLine("Result = {0}", value);
}
}
The output of the above code is −
Byte Array = 0A-14-1E Converting bytes at index 1-2: Byte 1: 20 (0x14) Byte 2: 30 (0x1E) Result = 7700
How It Works
The method combines two consecutive bytes using little-endian byte order. For bytes b1 and b2 at positions i and i+1, the result is calculated as:
result = b1 + (b2 * 256)
In the second example, bytes 20 (0x14) and 30 (0x1E) produce: 20 + (30 × 256) = 20 + 7680 = 7700.
Conclusion
The BitConverter.ToInt16() method efficiently converts two consecutive bytes from a byte array into a 16-bit signed integer using little-endian format. This method is particularly useful when working with binary data, network protocols, or file formats that store numeric values as byte sequences.
