C# BitConverter.ToUInt16() 方法


C# 中的 BitConverter.ToUInt16() 方法用於返回一個 16 位無符號整數,該整數是透過轉換位元組陣列中指定位置的兩個位元組而得到的。

語法

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

以上,val 是位元組陣列,而 begnIndex 是 val 中的起始位置。

示例

現在我們看一個示例 -

 動態演示

using System;
public class Demo {
   public static void Main() {
      byte[] arr = { 10, 20, 30, 40, 50};
      int count = arr.Length;
      Console.Write("Byte Array... ");
      for (int i = 0; i < count; i++) {
         Console.Write("
"+arr[i]);       }       Console.WriteLine("

Byte Array (String representation) = {0} ",       BitConverter.ToString(arr));       for (int i = 1; i < arr.Length - 1; i = i + 2) {          ushort res = BitConverter.ToUInt16(arr, i);          Console.WriteLine("
Value = "+arr[i]);          Console.WriteLine("Result = "+res);       }    } }

輸出

Byte Array...
10
20
30
40
50
Byte Array (String representation) = 0A-14-1E-28-32
Value = 20
Result = 7700
Value = 40
Result = 12840

示例

現在我們看另一個示例 -

 動態演示

using System;
public class Demo {
   public static void Main() {
      byte[] arr = { 0, 0, 1, 3, 5, 7, 10, 16, 20, 34, 42, 55, 66, 75};
      int count = arr.Length;
      Console.Write("Byte Array... ");
      for (int i = 0; i < count; i++) {
         Console.Write("
"+arr[i]);       }       Console.WriteLine("

Byte Array (String representation) = {0} ",       BitConverter.ToString(arr));       for (int i = 1; i < arr.Length - 1; i = i + 2) {          ushort res = BitConverter.ToUInt16(arr, i);          Console.WriteLine("
Value = "+arr[i]);          Console.WriteLine("Result = "+res);       }    } }

輸出

Byte Array...
0
0
1
3
5
7
10
16
20
34
42
55
66
75
Byte Array (String representation) = 00-00-01-03-05-07-0A-10-14-22-2A-37-42-4B
Value = 0
Result = 256
Value = 3
Result = 1283
Value = 7
Result = 2567
Value = 16
Result = 5136
Value = 34
Result = 10786
Value = 55
Result = 16951

更新於: 03-Dec-2019

272 瀏覽量

開啟你的 職業

完成該課程以獲得認證

開始學習
廣告
© . All rights reserved.