Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- namespace BitStream
- {
- public class BitWriter : IDisposable
- {
- private readonly Stream _outStream;
- private byte _buf;
- private int _counter;
- public BitWriter(Stream outStream)
- {
- _outStream = outStream;
- }
- public void Write(bool bit)
- {
- _counter++;
- _buf <<= 1;
- _buf |= (bit ? (byte) 1 : (byte) 0);
- if (_counter == 8)
- {
- Flush();
- }
- }
- private void Flush()
- {
- if (_counter == 0) return;
- _buf <<= 8 - _counter;
- _counter = 0;
- _outStream.WriteByte(_buf);
- _buf = 0;
- }
- public void Dispose()
- {
- Flush();
- _outStream.Dispose();
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- using (var bs = new BitWriter(new FileStream("test.bin", FileMode.Truncate)))
- {
- for (var i = 0; i < 16; i++)
- {
- bs.Write(i % 2 == 0);
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement