Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <bitset>
- // The Object that we put on the stream.
- // Pass in the group length, or default to 4.
- class bitpr
- {
- public:
- bitpr(size_t l = 4)
- :m_l(l){}
- private:
- // Class that actually does the work.
- class bitprn
- {
- public:
- bitprn(bitpr const& b, std::ostream& os)
- : m_l(b.m_l),
- m_s(os){}
- // The << operator for bitset<> types. Outputs the formatted
- // object to the stored stream then returns the stream.
- template<size_t N>
- std::ostream& operator<<(std::bitset<N> const& b)
- {
- int bit_len = b.size();
- for (int i = bit_len - 1; i >= 0; --i)
- {
- m_s << b[i];
- if ((i == (bit_len - bit_len % m_l)) ||
- (0 == i % m_l)) m_s << ' ';
- }
- return m_s << '\b';
- }
- // The << operator for all other types. Outputs the next object
- // to the stored stream then returns the stream.
- template<typename T>
- std::ostream& operator<<(T const& o)
- {
- return m_s << o;
- }
- private:
- size_t m_l;
- std::ostream& m_s;
- };
- friend bitpr::bitprn operator<<(std::ostream& os, bitpr const& b);
- private:
- char m_l;
- };
- // When you pass an object of type bitpr to an ostream it returns
- // an object of bitpr::bitprn that has overloaded the << operator for
- // all types. This will process the next object and then return the stream
- // to continue processing as normal.
- bitpr::bitprn operator<<(std::ostream& os, bitpr const& b)
- {
- return bitpr::bitprn(b, os);
- }
- using namespace std;
- int main(int, char**)
- {
- bitset<1> a;
- bitset<2> b;
- bitset<3> c;
- bitset<4> d;
- bitset<5> e;
- bitset<6> f;
- bitset<11> g;
- bitset<12> h;
- bitset<16> i;
- bitset<23> j;
- cout << "a: " << a << endl;
- cout << "b: " << b << endl;
- cout << "c: " << c << endl;
- cout << "d: " << d << endl;
- cout << "e: " << e << endl;
- cout << "f: " << f << endl;
- cout << "g: " << g << endl;
- cout << "h: " << h << endl;
- cout << "i: " << i << endl;
- cout << "j: " << j << endl;
- cout << "---------------------------------------\n";
- cout << "a: " << bitpr() << a << endl;
- cout << "b: " << bitpr() << b << endl;
- cout << "c: " << bitpr() << c << endl;
- cout << "d: " << bitpr() << d << endl;
- cout << "e: " << bitpr() << e << endl;
- cout << "f: " << bitpr() << f << endl;
- cout << "g: " << bitpr() << g << endl;
- cout << "h: " << bitpr() << h << endl;
- cout << "i: " << bitpr() << i << endl;
- cout << "j: " << bitpr(8) << j << endl;
- // Any other type is unchanged
- cout << "This is a string: " << bitpr() << "string" << endl;
- cout << "This is an int : " << bitpr() << 123 << endl;
- cout << "This is a float : " << bitpr() << 3.14159 << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement