问题
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?
回答1:
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).
回答2:
No it's not possible to write a single bit. You have to write at least a full byte. If you are in a situation that you want to write single bits, you can wait until you have 8 bits ready for writing (i.e. queue them up in memory) and then write out a full byte (i.e. using bit shifts etc. to combine those bits to a byte).
Also from Wikipedia:
Historically, a byte was the number of bits used to encode a single character of text in a computer and for this reason it is the basic addressable element in many computer architectures.
回答3:
If you are writing only bits, you can mix 8 bits into a single byte. But it is not possible to write a single bit.
回答4:
You could probably do it by read/modify/write. Why do you want to do such a thing? Whatever it is, find another way, pack bits into bytes, read/write boolean bytes and convert them back into bits, use ASCII '0' and '1' - amost anything except reading and writing one bit at a time.
来源:https://stackoverflow.com/questions/10057747/write-one-single-bit-to-binary-file-using-binarywriter