Export (0) Print
Expand All

BitConverter Class

Updated: August 2010

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

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

'Declaration
Public NotInheritable Class BitConverter
'Usage
You do not need to declare an instance of a static class in order to access its members.

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

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. Similarly, the relationship between the order of bytes in the array and the order of bytes in the values returned by the ToIntegerValue methods and the ToChar 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 Main()
          Dim value As Integer = 12345678
          Dim bytes() As Byte = BitConverter.GetBytes(value)
          Console.WriteLine(BitConverter.ToString(bytes))
    
          If BitConverter.IsLittleEndian Then
             bytes = ReverseBytes(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
             bytes = ReverseBytes(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 
    
       Private Function ReverseBytes(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
    
  • 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.

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

' 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

System.Object
  System.BitConverter

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

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 3.5, 2.0, 1.0

XNA Framework

Supported in: 3.0, 2.0, 1.0

Date

History

Reason

August 2010

Noted that the order of bytes in arrays in some ToIntegerValue conversion methods depend on computer architecture.

Customer feedback.

May 2010

Expanded the Remarks section.

Customer feedback.

Community Additions

ADD
Show:
© 2014 Microsoft