BitConverter 类

定义

将基数据类型转换为一个字节数组以及将一个字节数组转换为基数据类型。Converts base data types to an array of bytes, and an array of bytes to base data types.

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

示例

下面的代码示例演示如何使用几个 @no__t 0 类方法。The following code example illustrates the use of several BitConverter class methods.

// 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
*/
' 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

注解

@No__t 0 类有助于以一系列字节的形式操作其基本格式的值类型。The BitConverter class helps manipulate value types in their fundamental form, as a series of bytes. 字节被定义为8位无符号整数。A byte is defined as an 8-bit unsigned integer. @No__t-0 类包含用于在每个基元类型和字节数组之间进行转换的静态方法,如下表所示。The BitConverter class includes static methods to convert each of the primitive types to and from an array of bytes, as the following table illustrates.

类型Type 到字节转换To byte conversion 源字节转换From byte conversion
Boolean GetBytes(Boolean) ToBoolean
Char GetBytes(Char) ToChar
Double GetBytes(Double)

-or-

DoubleToInt64Bits(Double)
ToDouble

-or-

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 方法来往返数据,请确保 @no__t 重载和 @no__t*类型*方法指定相同的类型。If you use BitConverter methods to round-trip data, make sure that the GetBytes overload and the ToType method specify the same type. 如下面的示例所示,通过调用 ToUInt32 方法恢复表示有符号整数的数组可能会产生与原始值不同的值。As the following example illustrates, restoring an array that represents a signed integer by calling the ToUInt32 method can result in a value that is different from the original. 有关详细信息,请参阅在 BCL 团队博客中使用带符号的非十进制和按位值For more information, see the entry Working with Signed Non-Decimal and Bitwise Values in the BCL Team Blog.

using System;

public class Example
{
   public static void Main()
   {
      int value = -16;
      Byte[] bytes = BitConverter.GetBytes(value); 
      
      // Convert bytes back to Int32.
      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
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 方法重载返回的数组中的字节顺序(以及 @no__t 由 ToString(Byte[]) 方法返回的整数中的位的顺序以及由-2 方法返回的十六进制字符串顺序)取决于计算机体系结构是否为小字节序或大字节序。The order of bytes in the array returned by the GetBytes method overloads (as well as the order of bits in the integer returned by the DoubleToInt64Bits method and the order of hexadecimal strings returned by the ToString(Byte[]) method) depends on whether the computer architecture is little-endian or big-endian. 同样,由 ToIntegerValue方法和 @no__t 2 方法返回的数组中的字节顺序取决于计算机体系结构是小字节序还是大字节序。Similarly, the order of bytes in the array and returned by the ToIntegerValue methods and the ToChar method depends on whether the computer architecture is little-endian or big-endian. 体系结构的字节排序方式由 IsLittleEndian 属性指示,该属性在小 endian 系统上返回 true,在大字节序系统上返回 falseThe endianness of an architecture is indicated by the IsLittleEndian property, which returns true on little-endian systems and false on big-endian systems. 在小字节序系统上,低序位字节优先于高阶字节。On little-endian systems, lower-order bytes precede higher-order bytes. 在大字节序系统上,高位字节优先于低序位字节。On big-endian system, higher-order bytes precede lower-order bytes. 下表说明了将整数1234567890(0x499602D2)传递到 GetBytes(Int32) 方法所产生的字节数组中的差异。The following table illustrates the difference in the byte arrays that result from passing the integer 1,234,567,890 (0x499602D2) to the GetBytes(Int32) method. 字节按顺序列出,从索引0处的字节到索引3处的字节。The bytes are listed in order from the byte at index 0 to the byte at index 3.

小字节序Little-endian D2-02-96-49D2-02-96-49
大字节序Big-endian 49-96-02-D249-96-02-D2

由于某些方法的返回值取决于系统体系结构,因此在传输超出计算机边界的字节数据时要小心:Because the return value of some methods depends on system architecture, be careful when transmitting byte data beyond machine boundaries:

  • 如果保证发送和接收数据的所有系统都具有相同的字节序,则不会对数据执行任何操作。If all systems sending and receiving data are guaranteed to have the same endianness, nothing has be done to the data.

  • 如果发送和接收数据的系统可以具有不同的字节顺序,则始终按特定顺序传输数据。If systems sending and receiving data can have different endianness, always transmit data in a particular order. 这意味着数组中的字节顺序可能需要在发送它们之前或接收后进行反向。This means that the order of bytes in the array may have to be reversed either before sending them or after receiving them. 常见的约定是以网络字节顺序(大字节序顺序)传输数据。A common convention is to transmit data in network byte order (big-endian order). 下面的示例提供了以网络字节顺序发送整数值的实现。The following example provides an implementation for sending an integer value in network byte order.

    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
    
    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
    
  • 如果发送和接收数据的系统可以具有不同的字节序,并且要传输的数据包含带符号整数,请调用 @no__t 0 方法将数据转换为网络字节顺序,并使用 IPAddress.NetworkToHostOrder 方法将数据转换为所需的顺序。方.If systems sending and receiving data can have different endianness and the data to be transmitted consists of signed integers, call the IPAddress.HostToNetworkOrder method to convert the data to network byte order and the IPAddress.NetworkToHostOrder method to convert it to the order required by the recipient.

字段

IsLittleEndian

指示数据存储在此计算机体系结构中的字节顺序(“endianness”)。Indicates the byte order ("endianness") in which data is stored in this computer architecture.

方法

DoubleToInt64Bits(Double)

将指定的双精度浮点数转换为 64 位有符号整数。Converts the specified double-precision floating point number to a 64-bit signed integer.

GetBytes(Boolean)

以字节数组的形式返回指定的布尔值。Returns the specified Boolean value as a byte array.

GetBytes(Char)

以字节数组的形式返回指定的 Unicode 字符值。Returns the specified Unicode character value as an array of bytes.

GetBytes(Double)

以字节数组的形式返回指定的双精度浮点值。Returns the specified double-precision floating point value as an array of bytes.

GetBytes(Int16)

以字节数组的形式返回指定的 16 位有符号整数值。Returns the specified 16-bit signed integer value as an array of bytes.

GetBytes(Int32)

以字节数组的形式返回指定 32 位有符号整数值。Returns the specified 32-bit signed integer value as an array of bytes.

GetBytes(Int64)

以字节数组的形式返回指定 64 位带符号整数值。Returns the specified 64-bit signed integer value as an array of bytes.

GetBytes(Single)

以字节数组的形式返回指定的单精度浮点值。Returns the specified single-precision floating point value as an array of bytes.

GetBytes(UInt16)

以字节数组的形式返回指定的 16 位无符号整数值。Returns the specified 16-bit unsigned integer value as an array of bytes.

GetBytes(UInt32)

以字节数组的形式返回指定的 32 位无符号整数值。Returns the specified 32-bit unsigned integer value as an array of bytes.

GetBytes(UInt64)

以字节数组的形式返回指定的 64 位无符号整数值。Returns the specified 64-bit unsigned integer value as an array of bytes.

Int32BitsToSingle(Int32)

将指定的 32 位整数重新解释为单精度浮点值。Reinterprets the specified 32-bit integer as a single-precision floating-point value.

Int64BitsToDouble(Int64)

将指定的 64 位带符号整数重新解释成双精度浮点数。Reinterprets the specified 64-bit signed integer to a double-precision floating point number.

SingleToInt32Bits(Single)

将单精度浮点值转换为整数。Converts a single-precision floating-point value into an integer.

ToBoolean(Byte[], Int32)

返回由字节数组中指定位置的一个字节转换来的布尔值。Returns a Boolean value converted from the byte at a specified position in a byte array.

ToBoolean(ReadOnlySpan<Byte>)

将只读字节范围转换为布尔值。Converts a read-only byte span to a Boolean value.

ToChar(Byte[], Int32)

返回由字节数组中指定位置的两个字节转换来的 Unicode 字符。Returns a Unicode character converted from two bytes at a specified position in a byte array.

ToChar(ReadOnlySpan<Byte>)

将只读字节范围转换为字符。Converts a read-only byte span into a character.

ToDouble(Byte[], Int32)

返回由字节数组中指定位置的八个字节转换来的双精度浮点数。Returns a double-precision floating point number converted from eight bytes at a specified position in a byte array.

ToDouble(ReadOnlySpan<Byte>)

将只读字节范围转换为双精度浮点值。Converts a read-only byte span into a double-precision floating-point value.

ToInt16(Byte[], Int32)

返回由字节数组中指定位置的两个字节转换来的 16 位有符号整数。Returns a 16-bit signed integer converted from two bytes at a specified position in a byte array.

ToInt16(ReadOnlySpan<Byte>)

将只读字节范围转换为 16 位带符号整数。Converts a read-only byte span into a 16-bit signed integer.

ToInt32(Byte[], Int32)

返回由字节数组中指定位置的四个字节转换来的 32 位有符号整数。Returns a 32-bit signed integer converted from four bytes at a specified position in a byte array.

ToInt32(ReadOnlySpan<Byte>)

将只读字节范围转换为 32 位带符号整数。Converts a read-only byte span into a 32-bit signed integer.

ToInt64(Byte[], Int32)

返回由字节数组中指定位置的八个字节转换来的 64 位有符号整数。Returns a 64-bit signed integer converted from eight bytes at a specified position in a byte array.

ToInt64(ReadOnlySpan<Byte>)

将只读字节范围转换为 64 位带符号整数。Converts a read-only byte span into a 64-bit signed integer.

ToSingle(Byte[], Int32)

返回由字节数组中指定位置的四个字节转换来的单精度浮点数。Returns a single-precision floating point number converted from four bytes at a specified position in a byte array.

ToSingle(ReadOnlySpan<Byte>)

将只读字节范围转换为双精度浮点值。Converts a read-only byte span into a double-precision floating-point value.

ToString(Byte[])

将指定的字节数组的每个元素的数值转换为它的等效十六进制字符串表示形式。Converts the numeric value of each element of a specified array of bytes to its equivalent hexadecimal string representation.

ToString(Byte[], Int32)

将指定的字节子数组的每个元素的数值转换为它的等效十六进制字符串表示形式。Converts the numeric value of each element of a specified subarray of bytes to its equivalent hexadecimal string representation.

ToString(Byte[], Int32, Int32)

将指定的字节子数组的每个元素的数值转换为它的等效十六进制字符串表示形式。Converts the numeric value of each element of a specified subarray of bytes to its equivalent hexadecimal string representation.

ToUInt16(Byte[], Int32)

返回由字节数组中指定位置的两个字节转换来的 16 位无符号整数。Returns a 16-bit unsigned integer converted from two bytes at a specified position in a byte array.

ToUInt16(ReadOnlySpan<Byte>)

将只读字节范围转换为 16 位无符号整数。Converts a read-only byte-span into a 16-bit unsigned integer.

ToUInt32(Byte[], Int32)

返回由字节数组中指定位置的四个字节转换来的 32 位无符号整数。Returns a 32-bit unsigned integer converted from four bytes at a specified position in a byte array.

ToUInt32(ReadOnlySpan<Byte>)

将只读字节范围转换为 32 位无符号整数。Converts a read-only byte span into a 32-bit unsigned integer.

ToUInt64(Byte[], Int32)

返回由字节数组中指定位置的八个字节转换来的 64 位无符号整数。Returns a 64-bit unsigned integer converted from eight bytes at a specified position in a byte array.

ToUInt64(ReadOnlySpan<Byte>)

将字节转换为无符号长整数。Converts bytes into an unsigned long.

TryWriteBytes(Span<Byte>, Boolean)

将布尔值转换为字节范围。Converts a Boolean into a span of bytes.

TryWriteBytes(Span<Byte>, Char)

将字符转换为字节范围。Converts a character into a span of bytes.

TryWriteBytes(Span<Byte>, Double)

将双精度浮点值转换为字节范围。Converts a double-precision floating-point value into a span of bytes.

TryWriteBytes(Span<Byte>, Int16)

将 16 位带符号整数转换为字节范围。Converts a 16-bit signed integer into a span of bytes.

TryWriteBytes(Span<Byte>, Int32)

将 32 位带符号整数转换为字节范围。Converts a 32-bit signed integer into a span of bytes.

TryWriteBytes(Span<Byte>, Int64)

将 64 位带符号整数转换为字节范围。Converts a 64-bit signed integer into a span of bytes.

TryWriteBytes(Span<Byte>, Single)

将双精度浮点值转换为字节范围。Converts a double-precision floating-point value into a span of bytes.

TryWriteBytes(Span<Byte>, UInt16)

将无符号 16 位整数转换为字节范围。Converts an unsigned 16-bit integer into a span of bytes.

TryWriteBytes(Span<Byte>, UInt32)

将 32 位无符号整数转换为字节范围。Converts a 32-bit unsigned integer into a span of bytes.

TryWriteBytes(Span<Byte>, UInt64)

将无符号 64 位整数转换为字节范围。Converts an unsigned 64-bit integer into a span of bytes.

适用于

另请参阅