山东mip网站建设搜索引擎免费登录入口
本文讲述在C#中,怎样使用 BitConverter 类将字节数组转换为 int 然后又转换回字节数组的过程。
为什么需要这样呢?这是因为,比如说,在从网络读取字节之后,可能需要将字节转换为内置数据类型。 除了示例中的 ToInt32(Byte[], Int32) 方法之外,下面还列出了一些 BitConverter 类中将字节(来自字节数组)转换为其他内置类型的方法。
bool ToBoolean(Byte[], Int32)
char ToChar(Byte[], Int32)
double ToDouble(Byte[], Int32)
short ToInt16(Byte[], Int32)
int ToInt32(Byte[], Int32)
long ToInt64(Byte[], Int32)
float ToSingle(Byte[], Int32)
ushort ToUInt16(Byte[], Int32)
uint ToUInt32(Byte[], Int32)
ulong ToUInt64(Byte[], Int32)
下面的例子会初始化字节数组,并在计算机体系结构为 little-endian(即首先存储最低有效字节)的情况下反转数组,然后调用 ToInt32(Byte[], Int32) 方法以将数组中的四个字节转换为 int。 ToInt32(Byte[], Int32) 的第二个参数指定字节数组的起始索引。
注意:输出可能会根据字节大小端而不同。
byte[] bytes = { 0, 0, 0, 25 };
// 倘若系统架构是little-endian(小端序),则将字节数组反转。
if (BitConverter.IsLittleEndian)
Array.Reverse(bytes);
int i = BitConverter.ToInt32(bytes, 0);
Console.WriteLine("int: {0}", i);
// 输出: int: 25
在下面的例子中,将调用 BitConverter 类的 GetBytes(Int32) 方法,将 int 转换为字节数组。
注意:输出可能会根据计算机体系结构的字节顺序而不同。
byte[] bytes = BitConverter.GetBytes(201805978);
Console.WriteLine("byte array: " + BitConverter.ToString(bytes));
// 输出: byte array: 9A-50-07-0C
参考:
1. 《BitConverter class》: https://learn.microsoft.com/en-us/dotnet/api/system.bitconverter
2. 《理解字节序 · 阮一峰》: https://www.ruanyifeng.com/blog/2016/11/byte-order.html