Writing one bit to a binary using BinaryWriter

I want to write one 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 bit. Is it possible?

+2
source share
4 answers

You cannot save only 1 bit in a file. Almost all modern file systems and devices store data in 8-bit segments, aka bytes or octets.

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

+3
source

. . , , , 8 , (.. ), (, .., ).

Wikipedia:

, , .

+8

, 8 . .

0

Perhaps you could do this by reading / modifying / writing. Why do you want to do this? Whatever it is, find another way, put the bits in bytes, read / write logical bytes and convert them back to bits, use ASCII '0' and '1' - use something other than reading and writing one bit at a time .

0
source

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


All Articles