Bit class

A class that stores an integer in bits.

bit.h:

#ifndef YZZ_BIT_H
#define YZZ_BIT_H
#include <iostream>

class bit{
   bool* _bits;
public:
   bit(int num);
   virtual ~bit();
   bool operator[] (const int i) const;
   bool& operator[] (const int i);
};

std::ostream & operator<<(std::ostream &os, const bit& b);

#endif

bit.cpp:

#include "bit.h"
bit::bit(int num){
   int i = sizeof(int)*8;
   _bits = new bool[i];
   for (;i--;_bits[i] = num & 1 << i){}
}

bool bit::operator[] (const int i) const{
   return _bits[i];
}

bool& bit::operator[] (const int i){
   return _bits[i];
}

bit::~bit(){
   delete[] _bits;
}

std::ostream & operator<<(std::ostream &os, const bit& b){
   for (int i = sizeof(int)*8;i--;os << !!b[i]){}
   return os;
}

Leave a comment