tags:

views:

507

answers:

3

How to write bits (not bytes) to a file with c#, .net? I'm preety stuck with it.
Edit: i'm looking for a different way that just writing every 8 bits as a byte

A: 

You will have to use bitshifts or binary arithmetic, as you can only write one byte at a time, not individual bits.

Aistina
+6  A: 

The smallest amount of data you can write at one time is a byte.

If you need to write individual bit-values. (Like for instance a binary format that requires a 1 bit flag, a 3 bit integer and a 4 bit integer); you would need to buffer the individual values in memory and write to the file when you have a whole byte to write. (For performance, it makes sense to buffer more and write larger chunks to the file).

driis
unfortunately this is what i expected. i just wanted to avoid the problem with writing a number of bits that don't divide by 8 but i'll have to handle it
agnieszka
+3  A: 
  1. Accumulate the bits in a buffer (a single byte can qualify as a "buffer")
  2. When adding a bit, left-shift the buffer and put the new bit in the lowest position using OR
  3. Once the buffer is full, append it to the file
Jen