如何:将字节数组转换为 int(C# 编程指南)How to: Convert a byte Array to an int (C# Programming Guide)

此示例演示如何使用 BitConverter 类将字节数组转换为 int 然后又转换回字节数组。This example shows you how to use the BitConverter class to convert an array of bytes to an int and back to an array of bytes. 例如,在从网络读取字节之后,可能需要将字节转换为内置数据类型。You may have to convert from bytes to a built-in data type after you read bytes off the network, for example. 除了示例中的 ToInt32(Byte[], Int32) 方法之外,下表还列出了 BitConverter 类中将字节(来自字节数组)转换为其他内置类型的方法。In addition to the ToInt32(Byte[], Int32) method in the example, the following table lists methods in the BitConverter class that convert bytes (from an array of bytes) to other built-in types.

返回类型Type returned 方法Method
bool ToBoolean(Byte[], Int32)ToBoolean(Byte[], Int32)
char ToChar(Byte[], Int32)ToChar(Byte[], Int32)
double ToDouble(Byte[], Int32)ToDouble(Byte[], Int32)
short ToInt16(Byte[], Int32)ToInt16(Byte[], Int32)
int ToInt32(Byte[], Int32)ToInt32(Byte[], Int32)
long ToInt64(Byte[], Int32)ToInt64(Byte[], Int32)
float ToSingle(Byte[], Int32)ToSingle(Byte[], Int32)
ushort ToUInt16(Byte[], Int32)ToUInt16(Byte[], Int32)
uint ToUInt32(Byte[], Int32)ToUInt32(Byte[], Int32)
ulong ToUInt64(Byte[], Int32)ToUInt64(Byte[], Int32)

示例Example

此示例初始化字节数组,并在计算机体系结构为 little-endian(即首先存储最低有效字节)的情况下反转数组,然后调用 ToInt32(Byte[], Int32) 方法以将数组中的四个字节转换为 intThis example initializes an array of bytes, reverses the array if the computer architecture is little-endian (that is, the least significant byte is stored first), and then calls the ToInt32(Byte[], Int32) method to convert four bytes in the array to an int. ToInt32(Byte[], Int32) 的第二个参数指定字节数组的起始索引。The second argument to ToInt32(Byte[], Int32) specifies the start index of the array of bytes.

备注

输出可能会根据计算机体系结构的 endian 设置而不同。The output may differ depending on the endianess of your computer's architecture.

byte[] bytes = { 0, 0, 0, 25 };

// If the system architecture is little-endian (that is, little end first),
// reverse the byte array.
if (BitConverter.IsLittleEndian)
    Array.Reverse(bytes);

int i = BitConverter.ToInt32(bytes, 0);
Console.WriteLine("int: {0}", i);
// Output: int: 25

示例Example

在本示例中,将调用 BitConverter 类的 GetBytes(Int32) 方法,将 int 转换为字节数组。In this example, the GetBytes(Int32) method of the BitConverter class is called to convert an int to an array of bytes.

备注

输出可能会根据计算机体系结构的 endian 设置而不同。The output may differ depending on the endianess of your computer's architecture.

byte[] bytes = BitConverter.GetBytes(201805978);
Console.WriteLine("byte array: " + BitConverter.ToString(bytes));
// Output: byte array: 9A-50-07-0C

请参阅See also