New and improved binary class
Right... here it is - flames and comments all welcome:
#ifndef __BINARY__
#define __BINARY__
#include <iostream>
#include <string>
#include <limits>
#include <exception>
class binary
{
public:
class bad_size : public std::exception
{
virtual const char* what() const throw()
{
return "Number of Bits != Number of digits!";
}
} bad_size;
class bad_range : public std::exception
{
virtual const char* what() const throw()
{
return "Out of Range";
}
} bad_range;
template <typename T>
binary(const T& n)
{
const unsigned int bits =
std::numeric_limits<T>::digits; for (unsigned int i = 0; i < bits; i++)
digits.insert(digits.begin(), (n & (1 << i)) ?
'1' : '0');
// digits.insert(digits.begin(), 'E'); // tests
exception if (digits.size() != bits)
throw bad_size;
}
const bool test(const unsigned int n) const
{
if (n > digits.size() || n == 0)
throw bad_range;
return (digits[n - 1] == '1') ? true : false;
}
void set(const unsigned int n)
{
if (n > digits.size() || n == 0)
throw bad_range;
digits[n - 1] = '1';
}
friend std::ostream& operator<<(std::ostream& stream, const
binary& bin) {
return stream << bin.digits;
}
private:
std::string digits;
};
#endif // __BINARY__
--
http://www.munted.org.uk
Take a nap, it saves lives.