c# - C# 读取 DWORD 块中的文件
问题描述
我正在尝试将二进制文件读入字节数组。
我需要以 DWORD 块(或 4 个字节)读取文件,并将每个块存储到字节数组的单个元素中。这是我迄今为止所取得的成就。
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
var block = new byte[4];
while (true)
{
byte[] temp = new byte[4];
fs.Read(temp, 0, 4);
uint read = (byte)BitConverter.ToUInt32(temp, 0);
block[0] = read???
}
}
但是,将uint read
at 转换为元素block[0]
不起作用。我似乎找不到一种不会产生错误的方法。
感谢您的输入。
解决方案
// read all bytes from file
var bytes = File.ReadAllBytes("data.dat");
// create an array of dwords by using 4 bytes in the file
var dwords = Enumerable.Range(0, bytes.Length / 4)
.Select(index => BitConverter.ToUInt32(bytes, index * 4))
.ToArray();
// down-casting to bytes
var dwordsAsBytes = dwords.Select(dw => (byte)dw).ToArray();
推荐阅读
- amazon-web-services - DDB Raw AttributeValue 映射到 Object 之间的映射
- python - 如何按照指示从字符串中分离所有数字?
- matlab - 使用 Matlab 实现的 Prewitt 边缘检测器提供的边缘比内置函数厚
- uml - 用例规范包括和扩展关系
- c - 输入 n(一个正整数)数字并计算它们的总和、平均值和数字的平方和
- java - Eclipse 错误“构建路径包含重复条目”
- c++ - C++字符串中的At()函数和下标运算符有什么区别?
- networking - 如何使用不同的 IP 地址从 PC1 ping 到 PC2
- python - 如何删除列表中的字典元素?
- biopython - 我需要安装 MUSCLE 和 ClustalW 才能使用 biopython 工具吗?