Search code examples
c#bytebitwriterbinarywriter

Write one single bit to binary file using BinaryWriter


I want to write one single bit to a binary file.

using (FileStream fileStream = new FileStream(@"myfile.bin", FileMode.Create))
using (BinaryWriter binaryWriter = new BinaryWriter(fileStream))
{
    binaryWriter.Write((bool)10);
}

Something like binaryWriter.Write((bit)1);
When I use binaryWriter.Write((bool)1) the file has one byte, but I want to write one single bit. Is this possible?


Solution

  • You cannot store only 1 bit in a file. Almost all modern filesystems and hardware store data in segments of 8 bits, aka bytes or octets.

    If you want store a bit value in a file, store either 1 or 0 as a byte (00000001 or 00000000).