// bitbucket.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include using namespace std; const int SZ = 4; class BitBucket { unsigned char data[SZ]; int cnt; public : BitBucket(); // friend functions (of a class) are able to access private data // THIS IS NOT A MEMBER FUNCTION!!! friend ostream& operator << (ostream &, BitBucket &); friend int operator << (BitBucket &, const int); friend int operator >> (BitBucket &, const int n); BitBucket& operator + (BitBucket &); }; BitBucket& BitBucket::operator+ (BitBucket &b) { return *this; } BitBucket::BitBucket() { for (int i=0; i < SZ; i++) data[i] = 0xcc; // just put some data cnt = 0; } int operator >> (BitBucket &b, const int n) { unsigned char o = 0, r; // o : overflow, r : current remaining int i = 0; // iterate over all elements of data[] // starting from the 'MOST' significant // which in this example happens to be // the FIRST element of the data[] array do { r = b.data[i]; r <<= sizeof (unsigned char) * 8 - n; b.data[i] >>= n; b.data[i] |= o; o = r; } while (++i < SZ); b.cnt -= n; if (b.cnt < 0) b.cnt = 0; return o; } int operator << (BitBucket &b, const int n) { unsigned char o = 0, r; // o : overflow, r : current remaining int i = SZ - 1; // iterate over all elements of data[] // starting from the 'LEAST' significant // which in this example happens to be // the LAST element of the data[] array do { r = b.data[i]; r >>= sizeof(unsigned char)*8 - n; // size of data structure * bits - number of bits to move b.data[i] <<= n; b.data[i] |= o; o = r; } while (i--); b.cnt = b.cnt+n; if (b.cnt > sizeof(unsigned char) * 8 * SZ ) b.cnt = sizeof(unsigned char) * 8 * SZ ; return o; } ostream& operator << ( ostream &ostr, BitBucket &b) { cout << endl; for (int j=0; j < SZ; j++) { for (int i=sizeof(unsigned char) * 8 - 1; i>=0; i--) { if (b.data[j] & ( 1 << i ) ) ostr << 1; else ostr << 0; } cout << ' '; } cout << endl; return ostr; // return stream to be available for next operation } int operator +(const int a, BitBucket &b) { return 10; } int main() { BitBucket b; int a = (6 + b); // just a dummy showcase ((cout << "content before shift") << b); b << 5; ((cout << "content after shift left") << b); b >> 5; ((cout << "content after shift right") << b); return 0; }