BitConverter Class

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Converts base data types to an array of bytes, and an array of bytes to base data types.

Inheritance Hierarchy

System.Object
  System.BitConverter

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

Syntax

'Declaration
Public NotInheritable Class BitConverter
public static class BitConverter

The BitConverter type exposes the following members.

Methods

  Name Description
Public methodStatic memberSupported by Silverlight for Windows Phone DoubleToInt64Bits Converts the specified double-precision floating point number to a 64-bit signed integer.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetBytes(Boolean) Returns the specified Boolean value as an array of bytes.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetBytes(Char) Returns the specified Unicode character value as an array of bytes.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetBytes(Double) Returns the specified double-precision floating point value as an array of bytes.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetBytes(Int16) Returns the specified 16-bit signed integer value as an array of bytes.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetBytes(Int32) Returns the specified 32-bit signed integer value as an array of bytes.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetBytes(Int64) Returns the specified 64-bit signed integer value as an array of bytes.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetBytes(Single) Returns the specified single-precision floating point value as an array of bytes.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetBytes(UInt16) Returns the specified 16-bit unsigned integer value as an array of bytes.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetBytes(UInt32) Returns the specified 32-bit unsigned integer value as an array of bytes.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 GetBytes(UInt64) Returns the specified 64-bit unsigned integer value as an array of bytes.
Public methodStatic memberSupported by Silverlight for Windows Phone Int64BitsToDouble Converts the specified 64-bit signed integer to a double-precision floating point number.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 ToBoolean Returns a Boolean value converted from one byte at a specified position in a byte array.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 ToChar Returns a Unicode character converted from two bytes at a specified position in a byte array.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 ToDouble Returns a double-precision floating point number converted from eight bytes at a specified position in a byte array.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 ToInt16 Returns a 16-bit signed integer converted from two bytes at a specified position in a byte array.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 ToInt32 Returns a 32-bit signed integer converted from four bytes at a specified position in a byte array.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 ToInt64 Returns a 64-bit signed integer converted from eight bytes at a specified position in a byte array.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 ToSingle Returns a single-precision floating point number converted from four bytes at a specified position in a byte array.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 ToString(array<Byte[]) Converts the numeric value of each element of a specified array of bytes to its equivalent hexadecimal string representation.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 ToString(array<Byte[], Int32) Converts the numeric value of each element of a specified subarray of bytes to its equivalent hexadecimal string representation.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 ToString(array<Byte[], Int32, Int32) Converts the numeric value of each element of a specified subarray of bytes to its equivalent hexadecimal string representation.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 ToUInt16 Returns a 16-bit unsigned integer converted from two bytes at a specified position in a byte array.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 ToUInt32 Returns a 32-bit unsigned integer converted from four bytes at a specified position in a byte array.
Public methodStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 ToUInt64 Returns a 64-bit unsigned integer converted from eight bytes at a specified position in a byte array.

Top

Fields

  Name Description
Public fieldStatic memberSupported by Silverlight for Windows PhoneSupported by Xbox 360 IsLittleEndian Indicates the byte order ("endianess") in which data is stored in this computer architecture.

Top

Remarks

The BitConverter class helps manipulate value types in their fundamental form, as a series of bytes. A byte is defined as an 8-bit unsigned integer. 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.

If you use BitConverter methods to round-trip data, make sure that the GetBytes overload and the ToType method specify the same type. 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. For more information, see the entry Working with Signed Non-Decimal and Bitwise Values in the BCL Team Blog.

Module Example
   Public Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
      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)
      outputBlock.Text += String.Format("{0} = {1}: {2}",  
                        value, intValue, 
                        If(value.Equals(intValue), "Round-trips", "Does not round-trip")) + vbCrLf
         ' Convert bytes to UInt32.
         Dim uintValue As UInteger = BitConverter.ToUInt32(bytes, 0)
      outputBlock.Text += String.Format("{0} = {1}: {2}",  value, uintValue, 
                        If(value.Equals(uintValue), "Round-trips", "Does not round-trip")) + vbCrLf
   End Sub
End Module
' The example displays the following output:
'       -16 = -16: Round-trips
'       -16 = 4294967280: Does not round-trip
using System;

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      int value = -16;
      Byte[] bytes = BitConverter.GetBytes(value);

      // Convert bytes back to Int32.
      int intValue = BitConverter.ToInt32(bytes, 0);
      outputBlock.Text += String.Format("{0} = {1}: {2}",
                        value, intValue,
                        value.Equals(intValue) ? "Round-trips" : "Does not round-trip") + "\n";
      // Convert bytes to UInt32.
      uint uintValue = BitConverter.ToUInt32(bytes, 0);
      outputBlock.Text += String.Format("{0} = {1}: {2}", value, uintValue,
                        value.Equals(uintValue) ? "Round-trips" : "Does not round-trip") + "\n";
   }
}
// The example displays the following output:
//       -16 = -16: Round-trips
//       -16 = 4294967280: Does not round-trip

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(array<Byte[]) method) depends on whether the computer architecture is little-endian or big-endian. The 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. 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. The bytes are listed in order from the byte at index 0 to the byte at index 3.

Little-endian

D2-02-96-49

Big-endian

49-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.

    Module Example
       Public Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
          Dim value As Integer = 12345678
          Dim bytes() As Byte = BitConverter.GetBytes(value)
          outputBlock.Text &= BitConverter.ToString(bytes) & vbCrLf
    
          If BitConverter.IsLittleEndian Then
             bytes = ReverseBytes(bytes)
          End If
          outputBlock.Text &= BitConverter.ToString(bytes) & vbCrLf
          ' Call method to send byte stream across machine boundaries.
    
          ' Receive byte stream from beyond machine boundaries.
          outputBlock.Text &= BitConverter.ToString(bytes) & vbCrLf
          If BitConverter.IsLittleEndian Then
             bytes = ReverseBytes(bytes)
          End If
          outputBlock.Text &= BitConverter.ToString(bytes) & vbCrLf
          Dim result As Integer = BitConverter.ToInt32(bytes, 0)
          outputBlock.Text += String.Format("Original value: {0}", value) & vbCrLf
          outputBlock.Text += String.Format("Returned value: {0}", result) & vbCrLf
       End Sub
    
       Private Function ReverseBytes(ByVal inArray() As Byte) As Byte()
          Dim temp As Byte
          Dim highCtr As Integer = inArray.Length - 1
    
          For ctr As Integer = 0 To highCtr \ 2
             temp = inArray(ctr)
             inArray(ctr) = inArray(highCtr)
             inArray(highCtr) = temp
             highCtr -= 1
          Next
          Return inArray
       End Function
    End Module
    ' The example displays the following output on a little-endian system:
    '       4E-61-BC-00
    '       00-61-BC-4E
    '       00-61-BC-4E
    '       4E-61-BC-00
    '       Original value: 12345678
    '       Returned value: 12345678
    
    using System;
    
    public class Example
    {
       public static void Demo(System.Windows.Controls.TextBlock outputBlock)
       {
          int value = 12345678;
          byte[] bytes = BitConverter.GetBytes(value);
          outputBlock.Text += BitConverter.ToString(bytes) + "\n";
    
          if (BitConverter.IsLittleEndian)
             bytes = ReverseBytes(bytes);
    
          outputBlock.Text += BitConverter.ToString(bytes) + "\n";
          // Call method to send byte stream across machine boundaries.
    
          // Receive byte stream from beyond machine boundaries.
          outputBlock.Text += BitConverter.ToString(bytes) + "\n";
          if (BitConverter.IsLittleEndian)
             bytes = ReverseBytes(bytes);
    
          outputBlock.Text += BitConverter.ToString(bytes) + "\n";
          int result = BitConverter.ToInt32(bytes, 0);
          outputBlock.Text += String.Format("Original value: {0}", value) + "\n";
          outputBlock.Text += String.Format("Returned value: {0}", result) + "\n";
       }
    
       private static byte[] ReverseBytes(byte[] inArray)
       {
          byte temp;
          int highCtr = inArray.Length - 1;
    
          for (int ctr = 0; ctr < inArray.Length / 2; ctr++)
          {
             temp = inArray[ctr];
             inArray[ctr] = inArray[highCtr];
             inArray[highCtr] = temp;
             highCtr -= 1;
          }
          return inArray;
       }
    }
    // The example displays the following output on a little-endian system:
    //       4E-61-BC-00
    //       00-61-BC-4E
    //       00-61-BC-4E
    //       4E-61-BC-00
    //       Original value: 12345678
    //       Returned value: 12345678
    
  • 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.

Examples

The following code example illustrates the use of several BitConverter class methods.

' Example of BitConverter class methods.
Module Example

   Public Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)

      Const formatter As String = "{0,25}{1,30}"

      Dim aDoubl As Double = 0.1111111111111111
      Dim aSingl As Single = 0.1111111111111111
      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

      outputBlock.Text &= _
          "This example of methods of the BitConverter class" & _
          vbCrLf & "generates the following output." & vbCrLf & vbCrLf
      outputBlock.Text &= String.Format(formatter, "argument", "Byte array") & vbCrLf
      outputBlock.Text &= String.Format(formatter, "--------", "----------") & vbCrLf

      ' Convert values to Byte arrays and display them.
      outputBlock.Text &= String.Format(formatter, aDoubl, _
          BitConverter.ToString(BitConverter.GetBytes(aDoubl))) & vbCrLf
      outputBlock.Text &= String.Format(formatter, aSingl, _
          BitConverter.ToString(BitConverter.GetBytes(aSingl))) & vbCrLf
      outputBlock.Text &= String.Format(formatter, aLong, _
          BitConverter.ToString(BitConverter.GetBytes(aLong))) & vbCrLf
      outputBlock.Text &= String.Format(formatter, anInt, _
          BitConverter.ToString(BitConverter.GetBytes(anInt))) & vbCrLf
      outputBlock.Text &= String.Format(formatter, aShort, _
          BitConverter.ToString(BitConverter.GetBytes(aShort))) & vbCrLf
      outputBlock.Text &= String.Format(formatter, aChar, _
          BitConverter.ToString(BitConverter.GetBytes(aChar))) & vbCrLf
      outputBlock.Text &= String.Format(formatter, aBool, _
          BitConverter.ToString(BitConverter.GetBytes(aBool))) & vbCrLf
   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
// Example of BitConverter class methods.
using System;

class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      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;

      outputBlock.Text +=
          "This example of methods of the BitConverter class" +
          "\ngenerates the following output.\n" + "\n";
      outputBlock.Text += String.Format(formatter, "argument", "byte array") + "\n";
      outputBlock.Text += String.Format(formatter, "--------", "----------") + "\n";

      // Convert values to Byte arrays and display them.
      outputBlock.Text += String.Format(formatter, aDoubl,
          BitConverter.ToString(BitConverter.GetBytes(aDoubl))) + "\n";
      outputBlock.Text += String.Format(formatter, aSingl,
          BitConverter.ToString(BitConverter.GetBytes(aSingl))) + "\n";
      outputBlock.Text += String.Format(formatter, aLong,
          BitConverter.ToString(BitConverter.GetBytes(aLong))) + "\n";
      outputBlock.Text += String.Format(formatter, anInt,
          BitConverter.ToString(BitConverter.GetBytes(anInt))) + "\n";
      outputBlock.Text += String.Format(formatter, aShort,
          BitConverter.ToString(BitConverter.GetBytes(aShort))) + "\n";
      outputBlock.Text += String.Format(formatter, aChar,
          BitConverter.ToString(BitConverter.GetBytes(aChar))) + "\n";
      outputBlock.Text += String.Format(formatter, aBool,
          BitConverter.ToString(BitConverter.GetBytes(aBool))) + "\n";
   }
}

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

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference