Write one single bit to binary file using BinaryWriter

走远了吗. 提交于 2019-12-10 10:54:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!