淡若轻风

博客园 首页 新随笔 联系 订阅 管理

1. 使用 BitConverter.ToInt32(最常用)

csharp
byte[] bytes = { 0x78, 0x56, 0x34, 0x12 }; // 示例字节数组
int result = BitConverter.ToInt32(bytes, 0);
Console.WriteLine(result); // 输出: 305419896 (小端序: 0x12345678)

  注意: BitConverter 使用系统当前环境的字节序。在 Windows(x86/x64)上通常是小端序。

2. 手动转换(指定字节序)

小端序转换(低位在前)

byte[] bytes = { 0x78, 0x56, 0x34, 0x12 };
int result = bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24);
// 结果: 0x12345678 = 305419896

大端序转换(高位在前)

 
byte[] bytes = { 0x12, 0x34, 0x56, 0x78 };
int result = (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3];
// 结果: 0x12345678 = 305419896

  

3. 处理跨平台字节序(推荐)

public static int ToInt32(byte[] bytes, int startIndex, bool isLittleEndian = true)
{
    if (isLittleEndian == BitConverter.IsLittleEndian)
        return BitConverter.ToInt32(bytes, startIndex);
    else
        return bytes[startIndex] << 24 | 
               bytes[startIndex + 1] << 16 | 
               bytes[startIndex + 2] << 8 | 
               bytes[startIndex + 3];
}

  

4. 使用 MemoryMarshal(高性能,.NET Core 2.1+)

using System.Runtime.InteropServices;

byte[] bytes = { 0x78, 0x56, 0x34, 0x12 };
Span<byte> span = bytes.AsSpan();
int result = MemoryMarshal.Read<int>(span);

  

5. 处理小于4字节的数组

byte[] bytes = { 0x12, 0x34 }; // 只有2字节

// 方法1:填充到4字节
byte[] padded = new byte[4];
Array.Copy(bytes, padded, bytes.Length);
int result = BitConverter.ToInt32(padded, 0);

// 方法2:手动转换(小端序)
int result2 = bytes[0] | (bytes.Length > 1 ? bytes[1] << 8 : 0);

  

完整示例对比

 
byte[] bytes = { 0x12, 0x34, 0x56, 0x78 };

// 小端序解释(Windows默认)
int littleEndian = BitConverter.ToInt32(bytes, 0);
Console.WriteLine($"小端序: {littleEndian:X}"); // 输出: 78563412

// 大端序解释
int bigEndian = (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3];
Console.WriteLine($"大端序: {bigEndian:X}"); // 输出: 12345678

  

注意事项

  1. 数组长度:确保 byte[] 至少有4个字节(从起始索引开始)

  2. 字节序:网络协议通常使用大端序,Windows系统使用小端序

  3. 性能:手动转换比 BitConverter 稍快,但代码可读性较差

  4. 异常处理:使用 BitConverter 时如果数组长度不足会抛出异常

 

后记:每天去学一点,学一点呀学一点,永远学不完。

 

posted on 2026-06-17 16:37  淡若轻风  阅读(15)  评论(0)    收藏  举报