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 namespace System;
int main()
{
   String^ formatter = "{0,25}{1,30}";
   double aDoubl = 0.1111111111111111111;
   float aSingl = 0.1111111111111111111F;
   __int64 aLong = 1111111111111111111;
   int anInt = 1111111111;
   short aShort = 11111;
   __wchar_t aChar = L'*';
   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
*/
// 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)
ToDouble

-或-

Int64BitsToDouble
Int16 GetBytes(Int16) ToInt16
Int32 GetBytes(Int32) ToInt32
Int64 GetBytes(Int64) ToInt64
Single GetBytes(Single) ToSingle
UInt16 GetBytes(UInt16) ToUInt16
UInt32 GetBytes(UInt32) ToUInt32
UInt64 GetBytes(UInt64) ToUInt64

如果您使用 BitConverter 方法來來回數據,請確定 GetBytes 多載和 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 之整數中的位順序,) 取決於計算機架構是小到尾或大端。 同樣地,整數值方法ToChar和方法所傳To回的陣列位元組順序取決於計算機架構是小端或大端。 架構的結束性是由 IsLittleEndian 屬性表示,它會在小端系統與false大端系統上傳回true。 在小數端系統上,低序位元組在較高順序位元組之前。 在 big-endian 系統上,較高順序的位元組位於較低順序位元組之前。 下表說明將整數 1,234,567,890 (0x499602D2) GetBytes(Int32) 傳遞給 方法所產生的位元組數位差異。 位元組會依索引 0 的位元組到索引 3 的位元組順序列出。

位元組由小到大 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 將它轉換成收件者所需的訂單的方法。

欄位

IsLittleEndian

指出資料儲存在此電腦架構中的位元組順序 (字節順序)。

方法

DoubleToInt64Bits(Double)

將指定的雙精確度浮點數轉換為 64 位元帶正負號的整數。

DoubleToUInt64Bits(Double)

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

GetBytes(Boolean)

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

GetBytes(Char)

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

GetBytes(Double)

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

GetBytes(Half)

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

GetBytes(Int128)

將基底資料類型與位元組陣列相互轉換。

GetBytes(Int16)

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

GetBytes(Int32)

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

GetBytes(Int64)

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

GetBytes(Single)

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

GetBytes(UInt128)

將基底資料類型與位元組陣列相互轉換。

GetBytes(UInt16)

傳回指定的 16 位元不帶正負號的整數值為位元組陣列。

GetBytes(UInt32)

傳回指定的 32 位元不帶正負號的整數值為位元組陣列。

GetBytes(UInt64)

傳回指定的 64 位元不帶正負號的整數值為位元組陣列。

HalfToInt16Bits(Half)

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

HalfToUInt16Bits(Half)

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

Int16BitsToHalf(Int16)

將指定的16位帶正負號整數值重新解譯為半精確度浮點值。

Int32BitsToSingle(Int32)

將指定的 32 位元整數重新解譯為單精確度浮點數值。

Int64BitsToDouble(Int64)

將指定的 64 位元帶正負號整數重新解譯為雙精確度浮點數。

SingleToInt32Bits(Single)

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

SingleToUInt32Bits(Single)

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

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)

將基底資料類型與位元組陣列相互轉換。

ToInt128(ReadOnlySpan<Byte>)

將基底資料類型與位元組陣列相互轉換。

ToInt16(Byte[], Int32)

傳回從位元組陣列中指定位置的兩個位元組所轉換的 16 位元帶正負號的整數 (Signed Integer)。

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[])

將指定之位元組陣列的每一個元素之數值轉換成其對等的十六進位字串表示。

ToString(Byte[], Int32)

將指定之位元組子陣列的每一個元素之數值轉換成其對等的十六進位字串表示。

ToString(Byte[], Int32, Int32)

將指定之位元組子陣列的每一個元素之數值轉換成其對等的十六進位字串表示。

ToUInt128(Byte[], Int32)

將基底資料類型與位元組陣列相互轉換。

ToUInt128(ReadOnlySpan<Byte>)

將基底資料類型與位元組陣列相互轉換。

ToUInt16(Byte[], Int32)

傳回從位元組陣列中指定位置的兩個位元組所轉換的 16 位元不帶正負號的整數 (Unsigned Integer)。

ToUInt16(ReadOnlySpan<Byte>)

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

ToUInt32(Byte[], Int32)

傳回從位元組陣列中指定位置的四個位元組所轉換的 32 位元不帶正負號的整數。

ToUInt32(ReadOnlySpan<Byte>)

將唯讀位元組範圍轉換為 32 位元不帶正負號的整數。

ToUInt64(Byte[], Int32)

傳回從位元組陣列中指定位置的八個位元組所轉換的 64 位元不帶正負號的整數。

ToUInt64(ReadOnlySpan<Byte>)

將位元組轉換為不帶正負號的 long 類型。

TryWriteBytes(Span<Byte>, Boolean)

將布林值轉換為位元組範圍。

TryWriteBytes(Span<Byte>, Char)

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

TryWriteBytes(Span<Byte>, Double)

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

TryWriteBytes(Span<Byte>, Half)

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

TryWriteBytes(Span<Byte>, Int128)

將基底資料類型與位元組陣列相互轉換。

TryWriteBytes(Span<Byte>, Int16)

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

TryWriteBytes(Span<Byte>, Int32)

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

TryWriteBytes(Span<Byte>, Int64)

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

TryWriteBytes(Span<Byte>, Single)

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

TryWriteBytes(Span<Byte>, UInt128)

將基底資料類型與位元組陣列相互轉換。

TryWriteBytes(Span<Byte>, UInt16)

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

TryWriteBytes(Span<Byte>, UInt32)

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

TryWriteBytes(Span<Byte>, UInt64)

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

UInt16BitsToHalf(UInt16)

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

UInt32BitsToSingle(UInt32)

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

UInt64BitsToDouble(UInt64)

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

適用於

另請參閱