Saturday 23 March 2013

OOP344 Week 11: Object Oriented Binary String Print

The following is a class that prints the binary string. It also has a static varaible in the class to set the formatting of the string. If the string is formatted, then it will display the binary string with a space every 4th binary digit.

#include <iostream>

using namespace std;

class bits{
    unsigned int _val;
public:
    static bool formatted;  
    bits(unsigned int val){
        _val = val;
    }
    const char* displayBin() const{
        unsigned int m = 1 << sizeof(_val)*8-1;
        char* str = (formatted)?new char[sizeof(_val)*8 + (sizeof(_val)*8)/4 - 1 + 1]:new char[sizeof(_val)*8 + 1];
        int i = 0;
        while(m){
            if (formatted && (i+1)%5 == 0){
                str[i] = ' ';
            }
            else {
                str[i] = (_val & m)? '1' : '0';
                m = m >> 1;
            }
            i++;
        }
        str[i] = 0;
        return str;
    }
};
ostream& operator<<(ostream& os, const bits& b){
    os<<b.displayBin();
    return os;
}

bool bits::formatted = false; // by default false
int main(){
    char A = 0x5c;
    char B = 0x95;
    char C = 0;

    cout<<bits(A)<<endl;
    bits::formatted = true;
    cout<<bits(B)<<endl;
    return 0;
}

I should note that when setting statics in C++ using the class name, the scope resolution operator(::)needs to be used. Also, the default value of the static variable must be set outside the class.

No comments:

Post a Comment