You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

C#如何从byte array中提取指定格式数据到对应变量?

从Byte数组提取指定类型数据的解决方案

嘿,这个场景太常见了!在C#里从二进制字节数组里提取指定类型的数据,用BinaryReader是最顺手的方案(自动处理偏移和类型转换),当然手动计算偏移量也能搞定,我给你两种方式参考:

方式一:使用BinaryReader(推荐)

BinaryReader专门为二进制数据读取设计,能自动帮你管理读取位置,不用手动算偏移量,代码更简洁易维护:

byte[] buffer = File.ReadAllBytes("binarydata.bin");

// 将字节数组包装成内存流,供BinaryReader读取
using (var memoryStream = new MemoryStream(buffer))
using (var reader = new BinaryReader(memoryStream))
{
    // 提取长度为8的字符串:这里假设是ASCII编码,根据实际情况替换为UTF-8/UTF-16等
    // 二进制字符串常用\0填充到指定长度,所以用TrimEnd去掉末尾的空字符
    string value1 = Encoding.ASCII.GetString(reader.ReadBytes(8)).TrimEnd('\0');
    
    // 提取16位无符号整数
    ushort value2 = reader.ReadUInt16();
    
    // 提取长度为12的字符串
    string value3 = Encoding.ASCII.GetString(reader.ReadBytes(12)).TrimEnd('\0');
    
    // 提取32位无符号整数
    uint value4 = reader.ReadUInt32();
}

注意点:

  • 编码问题:如果你的二进制字符串不是ASCII编码,记得把Encoding.ASCII换成对应的编码(比如Encoding.UTF8)。
  • 字节序问题BinaryReader默认使用小端字节序(Little-Endian)。如果你的二进制文件是大端字节序(Big-Endian),需要先反转读取到的字节数组再转换,比如处理uint16的例子:
    byte[] value2Bytes = reader.ReadBytes(2);
    if (BitConverter.IsLittleEndian) // 系统是小端,文件是大端,所以反转字节
        Array.Reverse(value2Bytes);
    ushort value2 = BitConverter.ToUInt16(value2Bytes, 0);
    

方式二:手动计算偏移量

如果你不想依赖BinaryReader,也可以手动计算每个值在数组中的偏移位置,适合需要更精细控制的场景:

byte[] buffer = File.ReadAllBytes("binarydata.bin");
int offset = 0; // 记录当前读取的偏移位置

// 提取value1:从offset开始取8个字节
string value1 = Encoding.ASCII.GetString(buffer, offset, 8).TrimEnd('\0');
offset += 8; // 偏移量增加8

// 提取value2:从offset开始取2个字节转换为uint16
ushort value2 = BitConverter.ToUInt16(buffer, offset);
offset += 2; // 偏移量增加2

// 提取value3:从offset开始取12个字节
string value3 = Encoding.ASCII.GetString(buffer, offset, 12).TrimEnd('\0');
offset += 12; // 偏移量增加12

// 提取value4:从offset开始取4个字节转换为uint32
uint value4 = BitConverter.ToUInt32(buffer, offset);
offset += 4; // 偏移量增加4

同样,这里也要注意编码和字节序的问题,如果是大端字节序,转换前需要反转对应的字节数组。

内容的提问来源于stack exchange,提问作者Tim Svensson

火山引擎 最新活动