Use Byte [] to bool [] as flags and vice versa

Ok, so I have a byte [], which I use. File.ReadAllBytes(filename); My problem is that my program should treat the data from the file as an array of bools. I searched, but I could not find a way to get the correct and efficient conversion. An example is:

{ 00101011, 10111010 } ->
            { false, false, true, false, true, false, false, true, true,
              false, true, true, true, false, true, false }

I will also need to change the procedure.

Most of the solutions I came across included getting one boolean from each byte. those. the resulting array bool[]would have the same length as the array byte[], I don’t seem to understand how this is possible, how do 8 bits lead to one Boolean value? In my case, I should have a resulting array like:bool[bytes.Length * 8].

Thanks so much any help is much appreciated.

The implementation of one of the solutions that I tried to make work, but somehow incorrectly, because the received file, which is a copy of the file that I read, is damaged:

public static bool[] boolsFromFile(string filename)
    {
        List<bool> b = new List<bool>();
        using (FileStream fileStream = new FileStream(filename, FileMode.Open))
        using (BinaryReader read = new BinaryReader(fileStream))
        {
            while (fileStream.Position != fileStream.Length)
                b.Add(read.ReadBoolean());
        }
        return b.ToArray();
    }

    public static void boolsToFile(string filename, bool[] bools)
    {
        using (FileStream fileStream = new FileStream(filename, FileMode.Create))
        using (BinaryWriter write = new BinaryWriter(fileStream))
        {
            foreach (bool b in bools)
                write.Write(b);
        }
    }
+4
source share
2 answers

.NET bool "waste" seven bits . So there is no direct way to go from a byte to eight booleans.

You can use the BitArray class , see Converting C # Bytes to BitArray .

So something like this:

var bytes = File.ReadAllBytes(filename);
var bitArray = new BitArray(bytes);
bool ninthBit = bitArray[8];
+6
source

Easy with Linq

            byte[] input = new byte[] { 0x2b, 0xba };
            Boolean[][] results = input.Select(x => Enumerable.Repeat(x,8).Select((y, i) => ((y >> (7 - i)) & 1) == 0 ? false : true).ToArray()).ToArray();
0
source

Source: https://habr.com/ru/post/1625621/


All Articles