BitConverter.GetBytes Method (Int32)

 

Returns the specified 32-bit signed integer value as an array of bytes.

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

public static byte[] GetBytes(
	int value
)

Parameters

value
Type: System.Int32

The number to convert.

Return Value

Type: System.Byte[]

An array of bytes with length 4.

The order of bytes in the array returned by the GetBytes method depends on whether the computer architecture is little-endian or big-endian.

The following code example converts the bit patterns of Int32 values to Byte arrays with the GetBytes method.

using System;

class Example
{
    public static void Main( )
    {
        // Define an array of integers.
        int[] values = { 0, 15, -15, 0x100000,  -0x100000, 1000000000,
                         -1000000000, int.MinValue, int.MaxValue };

        // Convert each integer to a byte array.
        Console.WriteLine("{0,16}{1,10}{2,17}", "Integer", 
                          "Endian", "Byte Array");
        Console.WriteLine("{0,16}{1,10}{2,17}", "---", "------", 
                          "----------" );
        foreach (var value in values) {
          byte[] byteArray = BitConverter.GetBytes(value);
          Console.WriteLine("{0,16}{1,10}{2,17}", value, 
                            BitConverter.IsLittleEndian ? "Little" : " Big", 
                            BitConverter.ToString(byteArray));
        }
    }
}
// This example displays output like the following:
//              Integer    Endian       Byte Array
//                  ---    ------       ----------
//                    0    Little      00-00-00-00
//                   15    Little      0F-00-00-00
//                  -15    Little      F1-FF-FF-FF
//              1048576    Little      00-00-10-00
//             -1048576    Little      00-00-F0-FF
//           1000000000    Little      00-CA-9A-3B
//          -1000000000    Little      00-36-65-C4
//          -2147483648    Little      00-00-00-80
//           2147483647    Little      FF-FF-FF-7F

Universal Windows Platform
Available since 8
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1
Return to top
Show: