65.9K
CodeProject is changing. Read more.
Home

CBitStream - A simple C++ class for reading and writing variable-length data

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.23/5 (11 votes)

Jan 22, 2009

CPOL
viewsIcon

47528

downloadIcon

1267

An article on a simple C++ class for reading and writing variable-length data.

Introduction

This article is about a simple C++ class for reading and writing variable-length data streams. This feature is often required when programming compression routines like LZW, or when dealing with binary formats like Flash or PDF. It offers the developer a possibility to write binary chunks of custom size: like 11 bits, or 27 bits, etc. So, basically, output is byte-aligned, but the inner structure can hold different length data chunks.

Background

I found a working solution to this problem here on the CodeProject. But, this one is written in C# .NET, so I could not use it directly. I have not translated the original article, but written this one from scratch. I hope that someone will find this work useful.

Using the Code

Using the class CBitStream is very simple. Please see the code below:

#include "BitStream.h"

CBitStream bitStream;
bitStream.WriteBit(1);
bitStream.WriteByte('a');
bitStream.WriteWord(0x4441);
bitStream.WriteDWord(0x44410D0A);
bitStream.WriteData((LPBYTE)"ANSI text...", 12);
bitStream.WriteData((LPWORD)_T("UNICODE text..."), 15);
bitStream.SaveStream(_T("Enter output file path here..."));

Points of Interest

I have found that writing the CBitStream class described in this article was not too difficult as I have thought in first place. Also, now I have a simple tool that can help me in my everyday work.

History

  • CBitStream class version 1.0.