|
Programming, C++
[data compression]
RLE - run length encoding
MTF - move to front
BWT - burrows wheeler
Diatomic encoding
The static model
[bit io routines]
Bits & bytes
Bit io demo
|
'Bits & Bytes'
Converting Bytes to Bits (C++) 'returning a string containing bits of a byte'
I have tried to keep these examples as simple as possible, providing a function prototype, local or global declarations of variables, an example call & the function itself. All these routines are demonstrated in the BitRoutines C++ Demo [click to view] You can also download all the code behind them so that you can understand & implement these routines in your own code.
To use these code snipets in C++ depending on your programming environment, you may need to add the following header files as #include:
math.h, string, stdlib.h, iostream, stdio.h & fstream.
Method 1:
Returns a string containing the bits of a byte i.e. byte is a file char in, for example 'a' and size is a power of 2 (either pow(2,8) or 256 etc.)
copy code to clipboard.
AnsiString ByteToBitString(char byte, int size); // prototype
AnsiString buff; // var dec
buff = ByteToBitString('a', pow(2,8)); // call
AnsiString ByteToBitString(char byte, int size){ // function
register int t; AnsiString b = "";
size=size/2;
for(t=size; t>0; t=t/2)(byte & t) ? b+="1" : b+="0";
return b;
}

Method 2:
Returns a string containing the bits of a byte i.e. byte is a file char in, for example 'a' and bits is the number of bits to return i.e. 8
copy code to clipboard.
AnsiString ByteToBits(char byte, int bits); // prototype
AnsiString buff; // var dec
buff = ByteToBits(ch, 8); // call
AnsiString ByteToBits(char byte, int bits){ // function
register int t; AnsiString b = "";
t=1<<(bits-1);
while(t!=0){ (byte & t) ? b+="1" : b+="0"; t>>=1; }
return b;
}

Converting Bits to Bytes (C++) 'returning a byte from a string of bits'
This function returns the value relating to a byte as an integer 0-255. It uses recursive division & iteration through a sub-string of a string of bits adding the powers of 2 where a single '1' bit is flagged.
copy code to clipboard.
int BitsToByte(AnsiString s){
register int n=0, t, p=1;
for(t=128;t>0;t=t/2){
if(s.SubString(p,1)=="1") n=n+t;
p++;
}
return n;
}

Writing out 256 Consecutive Bytes (C++) 'writing out 256 consecutive bytes to a file (as binary)'
Writes out 256 Bytes to a file. There are lots of ways you can do this, throught the use of the STL or using stdout. Below is the code using ofstream.
copy code to clipboard.
ofstream out("test.txt", ios::out | ios::trunc | ios::binary); // overwrites existing data
for(unsigned int n=0;n<=255;n++) out.put((char) n); // output consecutive byte
out.close(); // close stream
|