BitConverter 類別

定義

將基礎資料型態轉換為位元組陣列,並將位元組陣列轉換為基礎資料型態。

public ref class BitConverter abstract sealed
public ref class BitConverter sealed
public static class BitConverter
public sealed class BitConverter
type BitConverter = class
Public Class BitConverter
Public NotInheritable Class BitConverter
繼承
BitConverter

範例

以下程式碼範例說明了多種 BitConverter 類別方法的使用。

// Example of BitConverter class methods.
using System;

class BitConverterDemo
{
    public static void Main( )
    {
        const string formatter = "{0,25}{1,30}";

        double  aDoubl  = 0.1111111111111111111;
        float   aSingl  = 0.1111111111111111111F;
        long    aLong   = 1111111111111111111;
        int     anInt   = 1111111111;
        short   aShort  = 11111;
        char    aChar   = '*';
        bool    aBool   = true;

        Console.WriteLine(
            "This example of methods of the BitConverter class" +
            "\ngenerates the following output.\n" );
        Console.WriteLine( formatter, "argument", "byte array" );
        Console.WriteLine( formatter, "--------", "----------" );

        // Convert values to Byte arrays and display them.
        Console.WriteLine( formatter, aDoubl,
            BitConverter.ToString( BitConverter.GetBytes( aDoubl ) ) );
        Console.WriteLine( formatter, aSingl,
            BitConverter.ToString( BitConverter.GetBytes( aSingl ) ) );
        Console.WriteLine( formatter, aLong,
            BitConverter.ToString( BitConverter.GetBytes( aLong ) ) );
        Console.WriteLine( formatter, anInt,
            BitConverter.ToString( BitConverter.GetBytes( anInt ) ) );
        Console.WriteLine( formatter, aShort,
            BitConverter.ToString( BitConverter.GetBytes( aShort ) ) );
        Console.WriteLine( formatter, aChar,
            BitConverter.ToString( BitConverter.GetBytes( aChar ) ) );
        Console.WriteLine( formatter, aBool,
            BitConverter.ToString( BitConverter.GetBytes( aBool ) ) );
    }
}

/*
This example of methods of the BitConverter class
generates the following output.

                 argument                    byte array
                 --------                    ----------
        0.111111111111111       1C-C7-71-1C-C7-71-BC-3F
                0.1111111                   39-8E-E3-3D
      1111111111111111111       C7-71-C4-2B-AB-75-6B-0F
               1111111111                   C7-35-3A-42
                    11111                         67-2B
                        *                         2A-00
                     True                            01
*/
open System

let print: obj -> obj -> unit = printfn "%25O%30O"

let aDoubl = 0.1111111111111111111
let aSingl = 0.1111111111111111111f
let aLong = 1111111111111111111L
let anInt = 1111111111
let aShort = 11111s
let aChar = '*'
let aBool = true

printfn "This example of methods of the BitConverter class\ngenerates the following output.\n"
print "argument" "byte array"
print "--------" "----------"

// Convert values to Byte arrays and display them.
print aDoubl (BitConverter.ToString(BitConverter.GetBytes aDoubl))

print aSingl (BitConverter.ToString(BitConverter.GetBytes aSingl))

print aLong (BitConverter.ToString(BitConverter.GetBytes aLong))

print anInt (BitConverter.ToString(BitConverter.GetBytes anInt))

print aShort (BitConverter.ToString(BitConverter.GetBytes aShort))

print aChar (BitConverter.ToString(BitConverter.GetBytes aChar))

print aBool (BitConverter.ToString(BitConverter.GetBytes aBool))


// This example of methods of the BitConverter class
// generates the following output.
//
//                  argument                    byte array
//                  --------                    ----------
//         0.111111111111111       1C-C7-71-1C-C7-71-BC-3F
//                 0.1111111                   39-8E-E3-3D
//       1111111111111111111       C7-71-C4-2B-AB-75-6B-0F
//                1111111111                   C7-35-3A-42
//                     11111                         67-2B
//                         *                         2A-00
//                      True                            01
' Example of BitConverter class methods.
Module BitConverterDemo

    Sub Main( )

        Const formatter As String = "{0,25}{1,30}"
 
        Dim aDoubl      As Double   = 0.1111111111111111111
        Dim aSingl      As Single   = 0.1111111111111111111
        Dim aLong       As Long     = 1111111111111111111
        Dim anInt       As Integer  = 1111111111
        Dim aShort      As Short    = 11111
        Dim aChar       As Char     = "*"c
        Dim aBool       As Boolean  = True

        Console.WriteLine( _
            "This example of methods of the BitConverter class" & _
            vbCrLf & "generates the following output." & vbCrLf )
        Console.WriteLine( formatter, "argument", "Byte array" )
        Console.WriteLine( formatter, "--------", "----------" )

        ' Convert values to Byte arrays and display them.
        Console.WriteLine( formatter, aDoubl, _
            BitConverter.ToString( BitConverter.GetBytes( aDoubl ) ) )
        Console.WriteLine( formatter, aSingl, _
            BitConverter.ToString( BitConverter.GetBytes( aSingl ) ) )
        Console.WriteLine( formatter, aLong, _
            BitConverter.ToString( BitConverter.GetBytes( aLong ) ) )
        Console.WriteLine( formatter, anInt, _
            BitConverter.ToString( BitConverter.GetBytes( anInt ) ) )
        Console.WriteLine( formatter, aShort, _
            BitConverter.ToString( BitConverter.GetBytes( aShort ) ) )
        Console.WriteLine( formatter, aChar, _
            BitConverter.ToString( BitConverter.GetBytes( aChar ) ) )
        Console.WriteLine( formatter, aBool, _
            BitConverter.ToString( BitConverter.GetBytes( aBool ) ) )
    End Sub
End Module

' This example of methods of the BitConverter class
' generates the following output.
' 
'                  argument                    Byte array
'                  --------                    ----------
'         0.111111111111111       1C-C7-71-1C-C7-71-BC-3F
'                 0.1111111                   39-8E-E3-3D
'       1111111111111111111       C7-71-C4-2B-AB-75-6B-0F
'                1111111111                   C7-35-3A-42
'                     11111                         67-2B
'                         *                         2A-00
'                      True                            01

備註

這個 BitConverter 類別幫助操作值型態的基本形式,也就是一連串位元組。 位元組定義為 8 位元的無號整數。 該 BitConverter 類別包含靜態方法,將每個原始型別轉換成或從一個位元組陣列轉換,如下表所示。

類型 轉為位元組轉換 從位元組轉換
Boolean GetBytes(Boolean) ToBoolean
Char GetBytes(Char) ToChar
Double GetBytes(Double)
-或-
DoubleToInt64Bits(Double)
-或-
DoubleToUInt64Bits(Double)
ToDouble
-或-
Int64BitsToDouble
-或-
UInt64BitsToDouble
Half GetBytes(Half)
-或-
HalfToInt16Bits(Half)
-或-
HalfToUInt16Bits(Half)
ToHalf
-或-
Int16BitsToHalf
-或-
UInt16BitsToHalf
Int16 GetBytes(Int16) ToInt16
Int32 GetBytes(Int32) ToInt32
Int64 GetBytes(Int64) ToInt64
Single GetBytes(Single)
-或-
SingleToInt32Bits(Single)
-或-
SingleToUInt32Bits(Single)
ToSingle
-或-
Int32BitsToSingle
-或-
UInt32BitsToSingle
UInt16 GetBytes(UInt16) ToUInt16
UInt32 GetBytes(UInt32) ToUInt32
UInt64 GetBytes(UInt64) ToUInt64

如果你用 BitConverter 方法來往返資料,請確保 GetBytes overload 和 ToType 方法指定相同的類型。 如以下範例所示,透過呼叫該 ToUInt32 方法還原代表有符號整數的陣列,可能會產生與原始值不同的值。 欲了解更多資訊,請參閱 「處理有號非十進位與位元值」。

using System;

public class Example
{
   public static void Main()
   {
      int value = -16;
      Byte[] bytes = BitConverter.GetBytes(value);

      // Convert bytes back to int.
      int intValue = BitConverter.ToInt32(bytes, 0);
      Console.WriteLine("{0} = {1}: {2}",
                        value, intValue,
                        value.Equals(intValue) ? "Round-trips" : "Does not round-trip");
      // Convert bytes to UInt32.
      uint uintValue = BitConverter.ToUInt32(bytes, 0);
      Console.WriteLine("{0} = {1}: {2}", value, uintValue,
                        value.Equals(uintValue) ? "Round-trips" : "Does not round-trip");
   }
}
// The example displays the following output:
//       -16 = -16: Round-trips
//       -16 = 4294967280: Does not round-trip
open System

let value = -16
let bytes = BitConverter.GetBytes value

// Convert bytes back to int.
let intValue = BitConverter.ToInt32(bytes, 0)
printfn $"""{value} = {intValue}: {if value.Equals intValue then "Round-trips" else "Does not round-trip"}"""

// Convert bytes to UInt32.
let uintValue = BitConverter.ToUInt32(bytes, 0)
printfn $"""{value} = {uintValue}: {if value.Equals uintValue then "Round-trips" else "Does not round-trip"}"""


// The example displays the following output:
//       -16 = -16: Round-trips
//       -16 = 4294967280: Does not round-trip
Module Example
   Public Sub Main()
      Dim value As Integer = -16
      Dim bytes() As Byte = BitConverter.GetBytes(value) 
      
      ' Convert bytes back to Int32.
      Dim intValue As Integer = BitConverter.ToInt32(bytes, 0)
      Console.WriteLine("{0} = {1}: {2}", 
                        value, intValue, 
                        If(value.Equals(intValue), "Round-trips", "Does not round-trip"))
      ' Convert bytes to UInt32.
      Dim uintValue As UInteger = BitConverter.ToUInt32(bytes, 0)
      Console.WriteLine("{0} = {1}: {2}", value, uintValue, 
                        If(value.Equals(uintValue), "Round-trips", "Does not round-trip"))
   End Sub
End Module
' The example displays the following output:
'       -16 = -16: Round-trips
'       -16 = 4294967280: Does not round-trip

方法超載回傳的陣列 GetBytes 中位元組的順序(以及方法回傳 DoubleToInt64Bits 的整數位元的順序)取決於電腦架構是小端序還是大端序。 同樣地,To 方法和方法回傳ToChar的位元組順序,取決於電腦架構是小端序還是大端序。 架構的端序性由性質IsLittleEndian表示,該性質在小端序系統和true大端序系統上皆有回傳false。 在小端序系統中,低階位元組會先於高階位元組。 在大端序系統中,高階位元組會先於低階位元組。 下表說明將整數 1,234,567,890(0x499602D2)傳遞給該 GetBytes(Int32) 方法所產生的位元組陣列差異。 位元組依序排列,從索引 0 的位元組到 3 的位元組。

Architecture 位元組陣列
小端序 D2-02-96-49
大端序 49-96-02-D2

由於某些方法的回傳值取決於系統架構,因此在傳送位元組資料越過機器邊界時需特別小心:

  • 如果所有傳送與接收資料的系統都保證具有相同的端序,那麼資料就不需要做任何處理。

  • 如果傳送與接收資料的系統具有不同的字序,則必須以特定順序傳送資料。 這表示陣列中位元組的順序可能需要在傳送前或接收後反轉。 常見的慣例是以網路位元組序(大端序)傳送資料。 以下範例提供了以網路位元組順序傳送整數值的實作。

    using System;
    
    public class Example
    {
       public static void Main()
       {
          int value = 12345678;
          byte[] bytes = BitConverter.GetBytes(value);
          Console.WriteLine(BitConverter.ToString(bytes));
    
          if (BitConverter.IsLittleEndian)
             Array.Reverse(bytes);
    
          Console.WriteLine(BitConverter.ToString(bytes));
          // Call method to send byte stream across machine boundaries.
    
          // Receive byte stream from beyond machine boundaries.
          Console.WriteLine(BitConverter.ToString(bytes));
          if (BitConverter.IsLittleEndian)
             Array.Reverse(bytes);
    
          Console.WriteLine(BitConverter.ToString(bytes));
          int result = BitConverter.ToInt32(bytes, 0);
          Console.WriteLine("Original value: {0}", value);
          Console.WriteLine("Returned value: {0}", result);
       }
    }
    // The example displays the following output on a little-endian system:
    //       4E-61-BC-00
    //       00-BC-61-4E
    //       00-BC-61-4E
    //       4E-61-BC-00
    //       Original value: 12345678
    //       Returned value: 12345678
    
    open System
    
    let value = 12345678
    let bytes = BitConverter.GetBytes value
    printfn $"{BitConverter.ToString bytes}"
    
    if BitConverter.IsLittleEndian then
        Array.Reverse bytes
    
    printfn $"{BitConverter.ToString bytes}"
    // Call method to send byte stream across machine boundaries.
    
    // Receive byte stream from beyond machine boundaries.
    printfn $"{BitConverter.ToString bytes}"
    if BitConverter.IsLittleEndian then
        Array.Reverse bytes
    
    printfn $"{BitConverter.ToString bytes}"
    let result = BitConverter.ToInt32(bytes, 0)
    
    printfn $"Original value: {value}"
    printfn $"Returned value: {result}"
    
    // The example displays the following output on a little-endian system:
    //       4E-61-BC-00
    //       00-BC-61-4E
    //       00-BC-61-4E
    //       4E-61-BC-00
    //       Original value: 12345678
    //       Returned value: 12345678
    
    Module Example
       Public Sub Main()
          Dim value As Integer = 12345678
          Dim bytes() As Byte = BitConverter.GetBytes(value)
          Console.WriteLine(BitConverter.ToString(bytes))
          
          If BitConverter.IsLittleEndian Then
             Array.Reverse(bytes) 
          End If
          Console.WriteLine(BitConverter.ToString(bytes))
          ' Call method to send byte stream across machine boundaries.
          
          ' Receive byte stream from beyond machine boundaries.
          Console.WriteLine(BitConverter.ToString(bytes))
          If BitConverter.IsLittleEndian Then     
             Array.Reverse(bytes)
          End If   
          Console.WriteLine(BitConverter.ToString(bytes))
          Dim result As Integer = BitConverter.ToInt32(bytes, 0)
          Console.WriteLine("Original value: {0}", value)
          Console.WriteLine("Returned value: {0}", result)
       End Sub
    End Module
    ' The example displays the following output on a little-endian system:
    '       4E-61-BC-00
    '       00-BC-61-4E
    '       00-BC-61-4E
    '       4E-61-BC-00
    '       Original value: 12345678
    '       Returned value: 12345678
    
  • 如果傳送與接收資料的系統有不同的端序,且要傳送的資料是有符號的整數,請呼叫 IPAddress.HostToNetworkOrder 將資料轉換為網路位元組順序的方法,以及 IPAddress.NetworkToHostOrder 將資料轉換為接收方所需的順序的方法。

欄位

名稱 Description
IsLittleEndian

表示此電腦架構中資料儲存的位元組順序(「恩序性」)。

方法

名稱 Description
BFloat16ToInt16Bits(BFloat16)

將基礎資料型態轉換為位元組陣列,並將位元組陣列轉換為基礎資料型態。

BFloat16ToUInt16Bits(BFloat16)

將基礎資料型態轉換為位元組陣列,並將位元組陣列轉換為基礎資料型態。

DoubleToInt64Bits(Double)

將指定的雙精度浮點數轉換為 64 位元有號整數。

DoubleToUInt64Bits(Double)

將指定的雙精度浮點數轉換為 64 位元無符號整數。

GetBytes(BFloat16)

將基礎資料型態轉換為位元組陣列,並將位元組陣列轉換為基礎資料型態。

GetBytes(Boolean)

傳回指定的布爾值做為位元組陣列。

GetBytes(Char)

傳回指定的 Unicode 字元值做為位元組陣列。

GetBytes(Double)

傳回指定的雙精確度浮點數做為位元組陣列。

GetBytes(Half)

傳回指定的半精確度浮點數做為位元組陣列。

GetBytes(Int128)

以位元組數位傳回指定的128位帶正負號整數值。

GetBytes(Int16)

以位元組數位傳回指定的16位帶正負號整數值。

GetBytes(Int32)

以位元組數位傳回指定的32位帶正負號整數值。

GetBytes(Int64)

以位元組數位傳回指定的64位帶正負號整數值。

GetBytes(Single)

傳回指定的單精度浮點值做為位元組陣列。

GetBytes(UInt128)

傳回指定的128位無符號整數值做為位元組陣列。

GetBytes(UInt16)

傳回指定的16位無符號整數值做為位元組陣列。

GetBytes(UInt32)

傳回指定的32位無符號整數值做為位元組陣列。

GetBytes(UInt64)

傳回指定的64位無符號整數值做為位元組陣列。

HalfToInt16Bits(Half)

將半精度浮點數轉換成16位元整數。

HalfToUInt16Bits(Half)

將指定的半精度浮點數轉換為16位元無符號整數。

Int16BitsToBFloat16(Int16)

將基礎資料型態轉換為位元組陣列,並將位元組陣列轉換為基礎資料型態。

Int16BitsToHalf(Int16)

將指定的 16 位元有號整數值重新詮釋為半精度浮點數值。

Int32BitsToSingle(Int32)

將指定的 32 位元整數重新詮釋為單精度浮點數值。

Int64BitsToDouble(Int64)

將指定的 64 位元有符號整數重新詮釋為雙精度浮點數。

SingleToInt32Bits(Single)

將單精度浮點數值轉換為整數。

SingleToUInt32Bits(Single)

將指定的單精度浮點數轉換為 32 位元無符號整數。

ToBFloat16(Byte[], Int32)

將基礎資料型態轉換為位元組陣列,並將位元組陣列轉換為基礎資料型態。

ToBFloat16(ReadOnlySpan<Byte>)

將基礎資料型態轉換為位元組陣列,並將位元組陣列轉換為基礎資料型態。

ToBoolean(Byte[], Int32)

回傳一個由位元組在指定位置轉換而成的布林值。

ToBoolean(ReadOnlySpan<Byte>)

將唯讀位元組區段轉換為布林值。

ToChar(Byte[], Int32)

回傳由指定位元組陣列中兩個位元組轉換而成的 Unicode 字元。

ToChar(ReadOnlySpan<Byte>)

將唯讀位元組區段轉換成字元。

ToDouble(Byte[], Int32)

回傳一個雙精度浮點數,該數字由位元組陣列中指定位置的八位元組轉換而成。

ToDouble(ReadOnlySpan<Byte>)

將唯讀位元組區間轉換成雙精度浮點數值。

ToHalf(Byte[], Int32)

回傳一個半精度浮點數,該數字由位元組陣列中指定位置的兩個位元組轉換而成。

ToHalf(ReadOnlySpan<Byte>)

將唯讀位元組區間轉換成半精度浮點數值。

ToInt128(Byte[], Int32)

傳回從位元組陣列中指定位置的16個字節轉換的128位帶正負號整數。

ToInt128(ReadOnlySpan<Byte>)

將只讀位元組範圍轉換成128位帶正負號的整數。

ToInt16(Byte[], Int32)

回傳一個 16 位元有號整數,該整數由位元組陣列中指定位置的兩個位元組轉換而成。

ToInt16(ReadOnlySpan<Byte>)

將一個唯讀位元組區間轉換成 16 位元有符號整數。

ToInt32(Byte[], Int32)

回傳一個 32 位元有號整數,該整數由指定位元組陣列中指定位置的四個位元組轉換而成。

ToInt32(ReadOnlySpan<Byte>)

將唯讀位元組區間轉換成 32 位元有號整數。

ToInt64(Byte[], Int32)

回傳一個 64 位元有號整數,該整數由位元組陣列中指定位置的八位元組轉換而成。

ToInt64(ReadOnlySpan<Byte>)

將唯讀位元組區間轉換成 64 位元有號整數。

ToSingle(Byte[], Int32)

回傳一個單精度浮點數,該數字由指定位元組陣列中指定位置的四個位元組轉換而成。

ToSingle(ReadOnlySpan<Byte>)

將唯讀位元組區間轉換成單精度浮點數值。

ToString(Byte[], Int32, Int32)

將指定子陣列中每個元素的數值轉換為其等效的十六進位字串表示法。

ToString(Byte[], Int32)

將指定子陣列中每個元素的數值轉換為其等效的十六進位字串表示法。

ToString(Byte[])

將指定位元組陣列中每個元素的數值轉換為其等效的十六進位字串表示法。

ToUInt128(Byte[], Int32)

回傳一個 128 位元的無符號整數,該整數由位元組陣列中指定位置的十六位元組轉換而成。

ToUInt128(ReadOnlySpan<Byte>)

將一個唯讀位元組區間轉換成 128 位元的無號整數。

ToUInt16(Byte[], Int32)

回傳一個 16 位元的無符號整數,該整數由位元組陣列中指定位置的兩個位元組轉換而成。

ToUInt16(ReadOnlySpan<Byte>)

將一個唯讀位元組區間轉換成 16 位元無號整數。

ToUInt32(Byte[], Int32)

回傳一個 32 位元的無符號整數,該整數由指定位元組陣列中指定位置的四個位元組轉換而成。

ToUInt32(ReadOnlySpan<Byte>)

將唯讀位元組區間轉換成 32 位元無號整數。

ToUInt64(Byte[], Int32)

回傳一個 64 位元的無符號整數,該整數由位元組陣列中指定位置的八位元組轉換而成。

ToUInt64(ReadOnlySpan<Byte>)

將位元組轉換成無符號的 long。

TryWriteBytes(Span<Byte>, BFloat16)

將基礎資料型態轉換為位元組陣列,並將位元組陣列轉換為基礎資料型態。

TryWriteBytes(Span<Byte>, Boolean)

將布爾值轉換成位元組範圍。

TryWriteBytes(Span<Byte>, Char)

將字元轉換成位元組範圍。

TryWriteBytes(Span<Byte>, Double)

將雙精確度浮點數轉換成位元組範圍。

TryWriteBytes(Span<Byte>, Half)

將半精確度浮點數轉換成位元組範圍。

TryWriteBytes(Span<Byte>, Int128)

將128位帶正負號的整數轉換成位元組範圍。

TryWriteBytes(Span<Byte>, Int16)

將16位帶正負號的整數轉換成位元組範圍。

TryWriteBytes(Span<Byte>, Int32)

將32位帶正負號的整數轉換成位元組範圍。

TryWriteBytes(Span<Byte>, Int64)

將64位帶正負號的整數轉換成位元組範圍。

TryWriteBytes(Span<Byte>, Single)

將單精度浮點數轉換成位元組範圍。

TryWriteBytes(Span<Byte>, UInt128)

將128位無符號整數轉換成位元組範圍。

TryWriteBytes(Span<Byte>, UInt16)

將不帶正負號的16位整數轉換成位元組範圍。

TryWriteBytes(Span<Byte>, UInt32)

將32位無符號整數轉換成位元組範圍。

TryWriteBytes(Span<Byte>, UInt64)

將不帶正負號的64位整數轉換成位元組範圍。

UInt16BitsToBFloat16(UInt16)

將基礎資料型態轉換為位元組陣列,並將位元組陣列轉換為基礎資料型態。

UInt16BitsToHalf(UInt16)

將指定的 16 位元無符號整數轉換為半精度浮點數。

UInt32BitsToSingle(UInt32)

將指定的 32 位元無符號整數轉換為單精度浮點數。

UInt64BitsToDouble(UInt64)

將指定的 64 位元無符號整數轉換為雙精度浮點數。

適用於

另請參閱