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してデータをラウンドトリップする場合は、オーバーロードと Type メソッドで同じ型がTo指定されていることを確認しますGetBytes。 次の例に示すように、 メソッドを呼び出して符号付き整数を表す配列を ToUInt32 復元すると、元の値とは異なる値になる可能性があります。 詳細については、「 符号付き 10 進数以外の値とビットごとの値の操作」を参照してください。

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

メソッドのオーバーロードによって返される配列内のバイトの順序 (およびメソッドによってGetBytesDoubleToInt64Bits返される整数内のビットの順序) は、コンピューター アーキテクチャがリトル エンディアンかビッグ エンディアンかによって異なります。 同様に、IntegerValue メソッドと メソッドToCharによってTo返される配列内のバイトの順序は、コンピューター アーキテクチャがリトル エンディアンかビッグ エンディアンかによって異なります。 アーキテクチャのエンディアンは、 プロパティによってIsLittleEndian示されます。このプロパティは、リトル エンディアン システムとfalseビッグ エンディアン システムでを返trueします。 リトル エンディアン システムでは、下位バイトが上位バイトより前になります。 ビッグ エンディアン システムでは、上位バイトが下位バイトの前に置きます。 次の表は、整数 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)

バイト配列内の指定位置にある 2 バイトから変換された Unicode 文字を返します。

ToChar(ReadOnlySpan<Byte>)

読み取り専用のバイト スパンを文字に変換します。

ToDouble(Byte[], Int32)

バイト配列内の指定位置にある 8 バイトから変換された倍精度浮動小数点数を返します。

ToDouble(ReadOnlySpan<Byte>)

読み取り専用のバイト スパンを倍精度浮動小数点の値に変換します。

ToHalf(Byte[], Int32)

バイト配列内の指定した位置にある 2 バイトから変換された laft-precision 浮動小数点数を返します。

ToHalf(ReadOnlySpan<Byte>)

読み取り専用バイト スパンを半精度浮動小数点値に変換します。

ToInt128(Byte[], Int32)

基本データ型をバイト配列に、バイト配列を基本データ型に変換します。

ToInt128(ReadOnlySpan<Byte>)

基本データ型をバイト配列に、バイト配列を基本データ型に変換します。

ToInt16(Byte[], Int32)

バイト配列内の指定位置にある 2 バイトから変換された 16 ビット符号付き整数を返します。

ToInt16(ReadOnlySpan<Byte>)

読み取り専用のバイト スパンを 16 ビット符号付き整数に変換します。

ToInt32(Byte[], Int32)

バイト配列内の指定位置にある 4 バイトから変換された 32 ビット符号付き整数を返します。

ToInt32(ReadOnlySpan<Byte>)

読み取り専用のバイト スパンを 32 ビット符号付き整数に変換します。

ToInt64(Byte[], Int32)

バイト配列内の指定位置にある 8 バイトから変換された 64 ビット符号付き整数を返します。

ToInt64(ReadOnlySpan<Byte>)

読み取り専用のバイト スパンを 64 ビット符号付き整数に変換します。

ToSingle(Byte[], Int32)

バイト配列内の指定位置にある 4 バイトから変換された単精度浮動小数点数を返します。

ToSingle(ReadOnlySpan<Byte>)

読み取り専用バイト スパンを単精度浮動小数点値に変換します。

ToString(Byte[])

指定されたバイト配列の各要素の数値をそれと等価な 16 進数文字列形式に変換します。

ToString(Byte[], Int32)

指定されたバイト サブ配列の各要素の数値をそれと等価な 16 進数文字列形式に変換します。

ToString(Byte[], Int32, Int32)

指定されたバイト サブ配列の各要素の数値をそれと等価な 16 進数文字列形式に変換します。

ToUInt128(Byte[], Int32)

基本データ型をバイト配列に、バイト配列を基本データ型に変換します。

ToUInt128(ReadOnlySpan<Byte>)

基本データ型をバイト配列に、バイト配列を基本データ型に変換します。

ToUInt16(Byte[], Int32)

バイト配列内の指定位置にある 2 バイトから変換された 16 ビット符号なし整数を返します。

ToUInt16(ReadOnlySpan<Byte>)

読み取り専用のバイト スパンを 16 ビット符号なし整数に変換します。

ToUInt32(Byte[], Int32)

バイト配列内の指定位置にある 4 バイトから変換された 32 ビット符号なし整数を返します。

ToUInt32(ReadOnlySpan<Byte>)

読み取り専用のバイト スパンを 32 ビット符号なし整数に変換します。

ToUInt64(Byte[], Int32)

バイト配列内の指定位置にある 8 バイトから変換された 64 ビット符号なし整数を返します。

ToUInt64(ReadOnlySpan<Byte>)

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 ビット符号なし整数を倍精度浮動小数点数に変換します。

適用対象

こちらもご覧ください