Advertisement
Guest User

Bit writer

a guest
Feb 1st, 2014
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.23 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3.  
  4. namespace BitStream
  5. {
  6.     public class BitWriter : IDisposable
  7.     {
  8.         private readonly Stream _outStream;
  9.         private byte _buf;
  10.         private int _counter;
  11.  
  12.         public BitWriter(Stream outStream)
  13.         {
  14.             _outStream = outStream;
  15.         }
  16.  
  17.         public void Write(bool bit)
  18.         {
  19.             _counter++;
  20.             _buf <<= 1;
  21.             _buf |= (bit ? (byte) 1 : (byte) 0);
  22.  
  23.             if (_counter == 8)
  24.             {
  25.                 Flush();
  26.             }
  27.         }
  28.  
  29.         private void Flush()
  30.         {
  31.             if (_counter == 0) return;
  32.  
  33.             _buf <<= 8 - _counter;
  34.             _counter = 0;
  35.             _outStream.WriteByte(_buf);
  36.             _buf = 0;
  37.         }
  38.  
  39.         public void Dispose()
  40.         {
  41.             Flush();
  42.             _outStream.Dispose();
  43.         }
  44.     }
  45.  
  46.     class Program
  47.     {
  48.         static void Main(string[] args)
  49.         {
  50.             using (var bs = new BitWriter(new FileStream("test.bin", FileMode.Truncate)))
  51.             {
  52.                 for (var i = 0; i < 16; i++)
  53.                 {
  54.                     bs.Write(i % 2 == 0);
  55.                 }
  56.             }
  57.         }
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement