一.什么是大端法与小端法
大端法与小端法是一个表示程序对象字节排列顺序的规则,我们举例说明:
假设int i=25,位于地址0x200处,它的十六进制值为0x00000019。
00是最高有效位,19是最低有效位;0x200是内存的低地址端,0x203是内存的高地址端。
1.大端表示法:低地址端 存放 高位字节
0x200 0x201 0x202 0x203
00 00 00 19
2.小端表示法:低地址端 存放 低位字节
0x200 0x201 0x202 0x203
19 00 00 00
二,字节数组转换为int型数据
1.将byte[] b = new byte[] { 0x19, 0x00, 0x00, 0x00 }放入BitConverter.ToInt32(b, 0)中,返回整数25;将byte[] b = new byte[] { 0x00, 0x00, 0x00,0x19 }放入BitConverter.ToInt32(b, 0)中,返回整数419430400
因此用BitConverter.ToInt32()将字节数组转换为整型数据前,必须将字节数组变成小端表示
class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
//整数25转为十六进制为0x19,大端表示为0x00000019,小端表示为0x19000000
byte[] b = new byte[] { 0x19, 0x00, 0x00, 0x00 };
//将字节数组转化为整数,BitConverter.ToInt32()中的字节数组b必须是四字节否则会出错
int _tempLength = BitConverter.ToInt32(b, 0);
Console.WriteLine("转换后的整数为: " + _tempLength);
}
}
2.
(1)下位机小端表示整数25后,将以下字节数组发送给上位机:
byte[] data=new byte[]{0x19,0x00};
上位机解析:
int i=BitConverter.ToInt32(new byte[] {data[0], data[1], 0x00, 0x00 }, 0);
(2) 下位机大端表示整数25后,将以下字节数组发送给上位机:
byte[] data=new byte[]{0x00,0x19};
上位机解析
int i=BitConverter.ToInt32(new byte[] {data[1], data[0], 0x00, 0x00 }, 0);
三,int型数据转化为字节数组
int i=25;用BitConverter.GetBytes(i);将int型转换为字节数组,结果为19 00 00 00,因此BitConverter.GetBytes()的转化结果是小端表示
internal static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
byte[] b = BitConverter.GetBytes(25);
string result = BitConverter.ToString(b).Replace("-", " ");
Console.WriteLine(result);//打印结果为19 00 00 00
}
}