Ok, so i have a byte[] that i get using
File.ReadAllBytes(filename);
My problem is that my program needs to treat the data from the file as an array of bools.
I have searched but i didn't manage to find a way to get a correct and efficient conversion.
An example would be:
{ 00101011, 10111010 } ->
{ false, false, true, false, true, false, false, true, true,
false, true, true, true, false, true, false }
I will also be needing to reverse the procedure.
Most Solutions i came across involved getting one boolean out of each byte. i.e, the resulting array of bool[]
had the same length as the byte[]
array, i don't seem to understand how this is possible, how do 8 bits result in only one boolean value?
In my case i need to have a resulting array as: bool[bytes.Length * 8].
Thanks alot, any help is highly appreciated.
Implementing one of the solutions i tryed to get this to work but it is somehow wrong because the resulting file, which is a copy of the file i read gets 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);
}
}