BitConverter.ToChar Method
[ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ]
Returns a Unicode character converted from two bytes at a specified position in a byte array.
Assembly: mscorlib (in mscorlib.dll)
Parameters
- value
- Type:
System.Byte
[]
An array.
- startIndex
- Type: System.Int32
The starting position within value.
| Exception | Condition |
|---|---|
| ArgumentException | startIndex equals the length of value minus 1. |
| ArgumentNullException | value is null. |
| ArgumentOutOfRangeException | startIndex is less than zero or greater than the length of value minus 1. |
The following code example converts elements of Byte arrays to Char values (Unicode characters) with the ToChar method.
// Example of the BitConverter.ToChar method. using System; class Example { const string formatter = "{0,5}{1,17}{2,8}"; // Convert two byte array elements to a char and display it. public static void BAToChar(System.Windows.Controls.TextBlock outputBlock, byte[] bytes, int index) { char value = BitConverter.ToChar(bytes, index); outputBlock.Text += String.Format(formatter, index, BitConverter.ToString(bytes, index, 2), value) + "\n"; } public static void Demo(System.Windows.Controls.TextBlock outputBlock) { byte[] byteArray = { 32, 0, 0, 42, 0, 65, 0, 125, 0, 197, 0, 168, 3, 41, 4, 172, 32 }; outputBlock.Text += String.Format( "This example of the BitConverter.ToChar( byte[ ], " + "int ) \nmethod generates the following output. It " + "converts \nelements of a byte array to char values.\n") + "\n"; outputBlock.Text += "initial byte array" + "\n"; outputBlock.Text += "------------------" + "\n"; outputBlock.Text += BitConverter.ToString(byteArray) + "\n"; outputBlock.Text += "\n"; outputBlock.Text += String.Format(formatter, "index", "array elements", "char") + "\n"; outputBlock.Text += String.Format(formatter, "-----", "--------------", "----") + "\n"; // Convert byte array elements to char values. BAToChar(outputBlock, byteArray, 0); BAToChar(outputBlock, byteArray, 1); BAToChar(outputBlock, byteArray, 3); BAToChar(outputBlock, byteArray, 5); BAToChar(outputBlock, byteArray, 7); BAToChar(outputBlock, byteArray, 9); BAToChar(outputBlock, byteArray, 11); BAToChar(outputBlock, byteArray, 13); BAToChar(outputBlock, byteArray, 15); } } /* This example of the BitConverter.ToChar( byte[ ], int ) method generates the following output. It converts elements of a byte array to char values. initial byte array ------------------ 20-00-00-2A-00-41-00-7D-00-C5-00-A8-03-29-04-AC-20 index array elements char ----- -------------- ---- 0 20-00 1 00-00 3 2A-00 * 5 41-00 A 7 7D-00 } 9 C5-00 � 11 A8-03 ? 13 29-04 ? 15 AC-20 ? */
Show: