المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Is there a way to write an bit to a binary file (NOT a byte) in C# ?



C# Programming
12-29-2009, 10:21 PM
Hello,
i'll try to be concret on my problem.

I want to convert a string: "alex" to bits (by bits I mean 0 and 1) and then write them into a binary file.
There are many ways to do this, but i've selected this:
private void MyWriteMethod()
{

byte[] bytes = UTF8Encoding.Default.GetBytes("alex");
Stream str = File.Create("test.bin");

BinaryWriter bw = new BinaryWriter(str);
BitArray bits = new BitArray(bytes);

for (int i = 0; i < bits.Length; i++)
{

bw.Write(bits.Get(i)); // the method Get of class BitArray returns the bit (true or false)
// from the position recived as parameter.
}
}

My problem is:
All goes well, but when I look for my file it occurs 32 bytes on my HDD.
Now to do a comparison, I create a new file and write by hand the text "alex". When I look for this new created file, I see that it occurs 4 bytes!!!!

My questions are:
1. Why is that ?? Can anyone explain to me this phenomenon ??
2. Can I occure the same amount of bytes using the bits ?
3. Afther that may I recive a code sample on how this can be done? I mean: how can I write bits to a binary file?

Thanks you for you're patience!
Alex Manolescu.