将“true,false或0,1”数组转换为字节数组,然后将其写入文件

本文关键字:数组 然后 字节数 字节 文件 转换 false true | 更新日期: 2023-09-27 18:35:39

我在问一个简单的问题,但我找不到最简单的方法,我的应用程序读取了一个小文件,只需从 8 字节文件中读取 8 个字节的单词"上传",将是 0,1... 或真假列表,长度为 8*8= 64 位,现在我已经在字符串数组和布尔值列表中拥有这 64 位,下面的代码更快,我只需要编辑代码以每次给我 8 位而不是 1 字节。与内存流

 string path = openFileDialog1.FileName;
 byte[] file = File.ReadAllBytes(path);
 MemoryStream memory = new MemoryStream(file);
 BinaryReader reader = new BinaryReader(memory);
 for (int i = 0; i <= file.Length - 1; i++)
 {
 byte result = reader.ReadByte();
 }

编辑此代码后,我只需要写回这些位

01110101-01110000-01101100-01101111-01100001-01100100-01100101-01100100

上传

到字节,然后将其写回有效文件。?? 我真的很累,因为我看到很多方法可以将字节数组写成文件,但没有一个位......我累了,因为我找不到出路!!

将“true,false或0,1”数组转换为字节数组,然后将其写入文件

您可以使用接受字节数组的 BitArray 构造函数:

var bitArray = new BitArray(new byte[] { result });

然后,您可以调用 bitArray.Get(n) 以获取位于 result 字节位置 n 处的位。

至于您的编辑,代码可以简化为:

string output = "";
byte[] fileBytes = File.ReadAllBytes(path);
var bitArray = new BitArray(fileBytes);
// Loop over all bits in the bitarray, containing all bytes read from the file.
for (int i = 0; i < bitArray.Length; i++)
{
    output += bitArray.Get(i) ? "1" : "0";
    // Output a dash every 8 characters.
    if ((i + 1) % 8 == 0)
    {
        output += "-"
    }
}
// Write `output` string to file.